How to properly implement a helper function in Haskell

Viewed 2177

The 'gridList' function description:

Takes two Integer inputs, x and y, and returns a list of tuples representing the coordinates of each cell from (1,1) to (x,y).

Example Output

$> gridList 3 3
$> [(1,1),(2,1),(3,1),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

Source Code

gridList :: Integer -> Integer -> [(Integer,Integer)]
gridList 1 1 = [(1,1)]
gridList 1 y = helper 1 y
gridList x y = (helper x y) ++ gridList (x-1) y
  where 
    helper :: Integer -> Integer -> [(Integer, Integer)]
    helper x 1 = [(x,1)]
    helper x y = (x,y) : (helper x (y-1))

Question: The code doesn't compile giving the following error: Variable not in scope referring to the line 3 where the helper is first introduced. Why doesn't the wheresolve this problem?

Thanks

2 Answers

In Haskell, where-bound definitions are in scope only in the equation immediately above the where block. This means that if you define a function using multiple equations, each of them gets a separate where block.

In your case, the definition of helper is in scope only for the third equation (line 4), but not for the first two.

In order to use the same helper definition for all branches, change the definition from three separate equations to a case expression:

gridList :: Integer -> Integer -> [(Integer,Integer)]
gridList x y = case (x, y) of
    (1, 1) -> [(1,1)]
    (1, _) -> helper 1 y
    _ -> (helper x y) ++ gridList (x-1) y
  where 
    helper :: Integer -> Integer -> [(Integer, Integer)]
    helper x 1 = [(x,1)]
    helper x y = (x,y) : (helper x (y-1))

The problem is that the scope of the where-clause covers only the last equation. I'd usually suggest using a case-expression instead of multiple equations. However, since you are doing pattern matches on two arguments, doing that here requires either matching on a pair, as in Fyodor Soikin's answer, or nested case-expressions:

gridList :: Integer -> Integer -> [(Integer,Integer)]
gridList x y = case x of
    1 -> case y of
        1 -> [(1,1)]
        _ -> helper 1 y
    _ -> helper x y ++ gridList (x-1) y
    where 
    helper :: Integer -> Integer -> [(Integer, Integer)]
    helper x 1 = [(x,1)]
    helper x y = (x,y) : helper x (y-1)

The least invasive workaround is probably using pattern guards:

gridList :: Integer -> Integer -> [(Integer,Integer)]
gridList x y
    | 1 <- x, 1 <- y = [(1,1)]
    | 1 <- x = helper 1 y
    | otherwise = helper x y ++ gridList (x-1) y
    where
    helper :: Integer -> Integer -> [(Integer, Integer)]
    helper x 1 = [(x,1)]
    helper x y = (x,y) : helper x (y-1)

As luqui suggests, other options include pulling helper out of the where-clause, and pushing the equations inside it (gridList = go where go 1 1 = [(1,1)] -- etc.).

Related