Haskell - variable not in scope error - beginner

Viewed 5309

I'm new to haskell and cannot work out what is wrong with my code. I keep getting a variable out of scope error.

Here is my code that i load into GHCi using :load

validLength :: String -> Bool
validLength xs | length xs == 26 = True
               | otherwise = False

I then type validLength aa which should return false but i'm getting an error.

*Main> validLength aa

<interactive>:1:13: error: Variable not in scope: aa :: String
2 Answers

Identifiers are not strings. (This is by no means special to Haskell, it's the same in most other languages.) So, when you give aa as the argument, GHC interprets it as the name of some variable. But, well, there is no variable with that name, at least not in scope, thus the error.

If you want to pass actually the string consisting of two a characters, then you should use a string literal. A string literal is simply a string in double quotes (again, that's the same way it is in many other programming languages).

*Main> validLength "aa"
False

Just to add a little thing to your code, don't be afraid to return an expression or function that returns a Boolean value:

:t (==)
(==) :: Eq a => a -> a -> Bool

so,

3==4 -> False
length [1,2,3] == 26 -> False

So your code could be simply:

validLength :: String -> Bool
validLength xs = length xs == 26 

or:

validLength :: String -> Bool
validLength =  (== 26) .  length 
Related