Search code examples
syntaxfunctional-programmingsmlfold

SML| foldl with if


I'm having this exercise which asks to count how many values in a boolean list are true.

I typed this:

fun countt xs = foldl (fn (x,y) => if x=true then y=y+1) 0 xs; 

which, apparently, is wrong. I'm getting the following error:

stdIn:54.21-54.24 Error: syntax error: deleting  RPAREN INT0

Now, I've searched a bit and found out that RPAREN is a Syntax error. But i can't figure why there's a problem in the first place.


Solution

  • In a functional programming language, an if expression must have both then branch and an else branch (and they must both have the same type). Your if expression only has a then branch.

    Additionally, x=true always evaluates to the same value as x so you can just write if x then ... else ....

    Finally, it looks like you're trying to write an assignment in the then branch. Remember that a foldl works by repeatedly passing the accumulator (y) to the function as it traverses the list with xs. So if you want to update the accumulator, all you have to do is return the updated value.