How to get the types right

I am learning Scala by converting some old projects from Java into Scala. Here is part of a Lisp system that uses union types to specify that a list cell can contain several types of thing. In the method stringOf(,), I would like to dispatch off the ‘actual’ type of the passed in union type. The code is obviously wrong because it is trying to match off the value rather than the type. What should I be doing in the match operation? Thank you!

// Lisp list cell with car and cdr

type Primitive = String | Boolean | Int | Double | Null

type Obj = Cell | Primitive

class Cell(var car : Obj, var cdr : Obj)
{


  // this getter is useful because the alternative is ((Cell)((Cell)x).cdr).car

  def cadr =
  {
    cdr.asInstanceOf[Cell].car
  }


  // return the string corresponding to the expression

  def stringOf(e : Obj) : String =
  {
    stringOf(e, false)
  }


  // boolean tail indicates whether the elements of a list are being printed,
  // so we can use standard list form (a b c) instead of literal nested form (a (b (c))).

  def stringOf(e : Obj, tail : Boolean) : String =
  {
    e match
        case String => e.asInstanceOf[String]
        case Int => e.toString
        case Double => e.toString
        case Boolean => e.toString
        case Null => ""
        case Cell =>
        {
            var sb = StringBuffer
            if (!tail) sb.append(")")
            sb.append(stringOf(e.asInstanceOf[Cell].car, false));
            if (e.asInstanceOf[Cell].cdr != null)
            {
                sb.append(" ");
                sb.append(stringOf(e.asInstanceOf[Cell].cdr, true));
            }
            if (!tail) sb.append(")");
            sb.toString();
        }
  }

}

You can pattern match on the types that make up a union type.
Let me show how it looks on Metals:

In my opinion this is a very bad way to learn Scala, we can kind of see this from the code you have, there are vars and asInstanceOfs everywhere, these are considered bad in Scala. You probably want to go with a proper book instead.

1 Like

I advice the book “scala for the impatient”.

Thank you. Of course that pattern makes sense. Thank you for the advice. I am refining the code to be more idiomatic; It is a work in progress, and I just needed to know how to do the pattern match.

1 Like

Cool, sorry for jumping to conclusions!
Programming in Scala 5th Edition shows these “typed patterns”, also how Java / Scala styles differ, the alternatives to vars and asInstanceOfs. That’s where I learned.

2 Likes

No problem. I’ve been browsing websites, and I am sure I saw the typed pattern before, but couldn’t remember it. It makes sense now to see it in a working program, so thank you. I downloaded the eBook Scala for the Impatient just now, and will also consider the one you suggested. It has to be an eBook because I live on a small island in the Med, and we have nothing like Amazon, or even bookshops that will order! Ordering anything takes many weeks anyway. But the weather is nice. I am used to the idea of FP and side-effect-free programming from being in Edinburgh in the 1970s with Rod Burstall and others, but when making an interpreter for a non-FP language, there is a limit to the amount of storage I want to turn over due to immutability!

Be careful about assumptions. While it’s true that there is some memory overhead, it may not be nearly as much as you think in practice. Scala’s immutable data structures (including case classes) are optimized to memory-share as much as possible between generations of data structures, and the JVM is good at reclaiming the garbage.

So yes, if you’re trying to build for a truly memory-constrained environment, this is a consideration. But in practice it’s never been an issue for me in relatively ordinary environments.

(I point this out because it’s extremely common for folks to think that immutability is necessarily memory-wasting, but while that was true once upon a time, that’s mostly long in the past.)

5 Likes

Now and then mutable state can be handy. [Ocaml does not have mutable state, so even simple sorting algorithms become complex]

1 Like

Agreed, but the majority of the useful mutable state tends to be function-local. It’s been quite a number of years since I’ve used a mutable member in the class, and I generally haven’t missed it.

1 Like

Now that I am in the process of translating a 60K line Java program into Scala, I am finding many places that can be done with immutable vals and data structures. The original reason for this was because a compositional style (instead of inheritance) suited the problem much better, but now, mutability will be the exception rather than the rule. This has brought the excitement back into programming!

3 Likes

“Clocksin”, now where have I heard that surname before?

In confess, I read the book by Ivan Bratko as my introduction to Prolog!

2 Likes

Yes, that’s me. I remember some good stories Ivan told about life in what was then Yugoslavia (now Slovenia). His book was good, too.

1 Like

OMG, when I saw ‘Clocksin’ I immediately thought ‘& Mellish’, but then I thought, Nah, can’t be.

Forgive me, but given your interest in both Scala and Lisp, I am taking the liberty to share the following, just in case you find them interesting at all:

The Functional Programming Triad of map, filter and fold

image.png

The Sieve of Eratosthenes - Part 1

image.png

The Sieve of Eratosthenes - Part 2 - Genuine versus Unfaithful Sieve

image.png

P.S. I belatedly checked your BIO, and lo and behold, it is you, the author, amongst other things, of Programming in Prolog. Respect!

I have not written anything in Prolog for years, but I did dare looking at Prolog in the following:

Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms

image.png

2 Likes

Also guilty in that I learned Prolog reading Bratko’s book and Kowalski’s one. Speaking of Bob Kowalski, note to self: remember to watch his youtube video, What is AI and how can we live with it?

1 Like

Aw thanks. I haven’t written anything in Prolog in decades, apart from casually testing an experimental compiler (in Java) I wrote some years ago. Prolog was so 1980s! I will have a look at the items you shared.

1 Like

Hah! Okay, I will admit that the name hadn’t registered with me, but I also used your book in my undergrad days, when I took a class on Prolog back around '85. Welcome to the Scala community!

2 Likes