Search code examples
listsmlsmlnj

"Can I write 2 instructions in one sml function like that '?


So I want to print a list with all the squares of numbers up to n.(in sml nj)

Example 
>printl 3 ;
> [0,1,4,9]

The thing is I have to print them using this function "creat" that creats a list with those:

(*print elements squares up to n*)
fun printl n =
( print(Int.toString(hd (creat n [])));  printl(n-1); );

(*creat a list *)
fun creat n acc = if n<0 then acc
else (creat (n-1) ((n*n)::acc) );

As you can see, I tried to call "creat" with [] in order to create the desired list of squares up to n and then I tried to print the head while recursively calling what's left without it (printl n-1).

I generate this error though: sml square.sml:2.55 Error: syntax error: replacing RPAREN with LET So I guess there something wrong with the number of instructions in printl?


Solution

  • The problem comes from the semi-colon after printl(n-1) because your compiler waits for another expression. Hence, the error message meaning that he won't accept an ) here but rather a let. So just remove that semi-colon.

    Note that the semi-colon has two different meanings:

    • either to sequence expressions a ; b ; c. So in that context a ; b ; is syntactically incorrect ;

    • or either to mark the end of a declaration at a top level in order to let the compiler know you are done with the current definition (as you have done for your two functions).