franza
franza

Reputation: 2327

Haskell: unexpected "Not in scope" error for simple function

This is very ad-hoc example describes Not in scope: isOne error that I have:

ignoreFirstOnes :: [Int] -> [Int]
ignoreFirstOnes (1:xs) = dropWhile isOne xs
ignoreFirstOnes xs     = xs
  where isOne = (== 1)

Strange that isOne function was defined in where, however compiler keeps complaining. I can rewrite that using guards or even to dropWhile (== 1) but I would like to understand how to make work the current example.

Upvotes: 3

Views: 75

Answers (1)

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44664

Names defined in a where clause are only in scope over the branch that the where clause is attached to.

This version of your definition will compile, because I attached the where clause to the branch of ignoreFirstOnes that uses isOne.

ignoreFirstOnes :: [Int] -> [Int]
ignoreFirstOnes (1:xs) = dropWhile isOne xs
    where isOne = (== 1)
ignoreFirstOnes xs = xs

Though note that this definition is equivalent to ignoreFirstOnes = dropWhile (==1), which I think is simpler.

Upvotes: 5

Related Questions