0

I'm very new to SML and I'm trying to write a function that determines whether a string is balanced or not. A balanced string is: 1. a string where the number of "(" occurrences is equal to the number of ")". 2. in every prefix ")" does not occur more than "(". For example : ")(" is not balanced because the second condition does not apply.

I wrote this code but I'm getting a compilation error:

fun balanceAux(s:string , i:int , c1:int , c2:int) : bool =
    if i = size(s)-1 then
        if c1=c2 then true
            else false
    else
        if c2>c1 then false
        else
            if (str(String.sub(s,i)) = "(") then balanceAux(s,i+1,c1+1,c2)
            else
                if (str(String.sub(s,i)) = ")") then balanceAux(s,i+1,c1,c2+1);
                else balanceAux(s,i+1,c1,c2);

fun balance(t:string) : bool =
balanceAux(t,0,0,0);

I'm getting 3 compilation errors:

inserting LPAREN

inserting LET

found at EOF

Any ideas what am I doing wrong? I read around that it might have to do with my code having an expression of:

If A then B else If C then D

but I cant understand what can I do.

Basilm
  • 23
  • 6

1 Answers1

0

You have a stray semicolon at the end of the 10th line.

It might feel strange coming to SML from imperative languages, but semicolons in SML are actually quite rare. In your example, semicolons are not necessary at all.

Note that if you are copy-pasting this into the SML/NJ REPL, you will need a single semicolon at the end to tell the REPL that you are done typing. However this is specific to interactive SML/NJ sessions.


A side note, unrelated to your compilation problem: the definition you gave for a balanced string isn't very good. Condition 2 implies that if the input string contains ")" at all, then it isn't balanced--consider the substring containing just ")"; clearly this substring has more occurances of ")" than "(".

Perhaps you meant that in every prefix, ")" does not occur more than "("?

Sam Westrick
  • 1,248
  • 1
  • 7
  • 9
  • Thanks alot! , I corrected it and I was able to fix it by even writing another code at all from scratch. – Basilm Nov 20 '17 at 19:27