persongr
persongr

Reputation: 11

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.

Upvotes: 1

Views: 514

Answers (2)

Pablo Adames
Pablo Adames

Reputation: 644

Just to complement the previous answer here are the suggested modifications:

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

The term in parenthesis is the first argument to foldl, the value 0 is the seed value and the xs is the sequence that will be folded. The function takes a value and the current element of the sequence xs.

The function must return a value of the same type of 0, an integer.

Upvotes: 0

Lambdageek
Lambdageek

Reputation: 12475

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.

Upvotes: 3

Related Questions