Sam
Sam

Reputation: 3

I get Error: syntax error: inserting ELSE ID when compiling my SML code and I don't know why

I am attending a Coursera class, and I am trying to do my homeworks.

We have to write an SML program that takes a list of cards (caracterised by their suit and rank) and returns true if they all have the same color and false otherwise.

Here is my code (i can't figure why its false, but i am quit a noob in programming):

datatype suit = Clubs | Diamonds | Hearts | Spades
datatype rank = Jack | Queen | King | Ace | Num of int 
type card = suit * rank

datatype color = Red | Black
datatype move = Discard of card | Draw 


fun card_color (c) = case c of
(Hearts,_) => Red
|(Diamonds,_)  => Red
|(_,_) => Black


fun all_same_color (cs) = case cs of
    [] => false
    |x::[] => true 
|x::y::[] =>  if card_color (x) = card_color (y) then true
|x::y::xs => if card_color(x)=card_color(y) then all_same_color(xs)
                        else false

Upvotes: 0

Views: 3052

Answers (2)

You cannot have an if ... then ... without an else ... case.

You attempt to do this here:

|x::y::[] =>  if card_color (x) = card_color (y) then true

Remember, if ... then ... else ... is an expression, and thus needs a value whether or not the condition is true or false.

In addition, if you get an if-then-else, where either the then or else parts are true or false directly, you can write it more succinctly. For instance,

if card_color(x)=card_color(y) then all_same_color(xs) else false

is the same as saying

card_color x = card_color y andalso all_same_color xs

Upvotes: 2

Roberto
Roberto

Reputation: 2185

I don't know that language but your last condition is incorrect (I assume is some kind of Haskell):

|x::y::xs => if card_color(x)=card_color(y) then all_same_color(xs)
                    else false

should be:

|x::y::xs => if card_color(x)=card_color(y) then all_same_color(y::xs)
                    else false

I don't know if (y::xs) is what I mean, that parameter should be a list with y followed by xs. Using that condition, your third case is redundant, so the last function should be:

fun all_same_color (cs) = case cs of
    [] => false
    |x::[] => true 
    |x::y::xs => if card_color(x)=card_color(y) then all_same_color(y::xs)
                    else false

Upvotes: 0

Related Questions