boss revs
boss revs

Reputation: 351

Haskell if statement is not working properly

Very simple code. It will get the third last item from a list.

list numbers = if length numbers > 3
then numbers!!(length numbers - 3) 

else "length must be greater than 2"

When i try to run it on the GHCI I keep getting this error however,

*Main> list [2,3,4]

<interactive>:65:7: No instance for (Num [Char])
 arising from the literal     `2'
 Possible fix: add an instance declaration for (Num [Char])
In the expression: 2
In the first argument of `list', namely `[2, 3, 4]'
In the expression: list [2, 3, 4]

Upvotes: 0

Views: 316

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153102

The types of the two expressions in the then and else clause must match. Since one side of the branch returns a list element, and the other side returns a string, ghci concludes that the list elements must be strings. But you specified [2,3,4], whose elements are numbers. Hence the complaint: it doesn't know how to turn a number into a String.

Consider returning a Maybe or Either value instead:

list numbers = if length numbers > 3
    then Right (numbers!!(length numbers - 3))
    else Left "length must be greater than 2" -- sic: 3, not 2

Upvotes: 2

Related Questions