5
votes

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
I think you mean validLength "aa". - leftaroundabout
You here make use of a variable aa which, likely, does not exists. If you want to pass a String, you should use validLength "aa". - Willem Van Onsem
@leftaroundabout thanks a lot, my mistake :-) - Alisha White
Note that operator == already returns a boolean. There is no need to check if that is true, and then return True/False accordingly. You can directly return the result of == e.g. isZero x = x == 0. - chi
I.e., validLength xs = length xs == 26. - chepner

2 Answers

4
votes

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
2
votes

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