Ramzi Khahil
Ramzi Khahil

Reputation: 5052

printing a list in SML

I want to print a list inside a help function, for debugging purpose. And for some reason it's not printing anything. Does anyone know what's wrong?
Here is some of my code:

local
....
and xx(LparenToken) = "LparenToken"
| xx(RparenToken) = "RparenToken"
| xx(QuoteToken) = "QuoteToken"
| xx(DotToken) = "DotToken"
| xx(VectorToken) = "VectorToken"
| xx(IntToken(a)) = "IntToken"
| xx(CharToken(a)) = "CharToken"
| xx(StringToken(a)) = "StringToken"
| xx(SymbolToken(a)) = "SymbolToken"
| xx(BoolToken(a)) = "BoolToken"

and readList(nil) = []
| readList(lst:SchemeToken list) = (map(print)((map(xx)(lst))); read(getFirstSexpr(lst))::readList(getRestSexpr(lst)))
...
in
    some functions..
end

i have tried this also:

and readList(nil) = []
| readList(lst:SchemeToken list) = (print "x"; read(getFirstSexpr(lst))::readList(getRestSexpr(lst)))

it is not printing. i get just the answer:

- Reader.stringToSexpr "#(a b (1 2 3) c)";
val it =
  Vector
    [Symbol "a",Symbol "b",Pair (Number 1,Pair (Number 2,Number 3)),
     Symbol "c"] : Sexpr

Upvotes: 2

Views: 8711

Answers (1)

Gian
Gian

Reputation: 13955

I suspect the problem is not with your list printing code - that's going to work fine, provided it is called with some data.

For reference, there's a nicer way to evaluate for effects with lists: List.app : ('a -> unit) -> 'a list -> unit. It's like List.map, but it doesn't construct a list as a return value. Another one you might like is String.concatWith, which often makes printing code easier, e.g.:

print (String.concatWith "\n" (map xx lst))

And as a final note, you've used lots of unnecessary parentheses there in your example code. You rarely need to parenthesise expressions - especially not if there is no function application involves (i.e., writing (lst) or (xx) is always just going to mean lst or xx, and does not resolve any ambiguity (because there is none). Similarly in your patterns, they could just as easily be written (IntToken a) without changing the meaning (and possibly adding to readability).

Upvotes: 5

Related Questions