Porco
Porco

Reputation: 393

Haskell quicksort: Parsing error with 'where'

I'm just starting to teach myself Haskell out of the book "Learn you a haskell for great good", and I rewote the quicksort in Chapter 5 using where:

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = smaller ++ [x] ++ bigger
    where smaller = quicksort [a | a <- xs, a <= x]
      bigger = quicksort [a |a <- xs, a > x]

but when I loaded it into GHCi 7.0.3, I got the following error:

parse error on input '='

The original code on the book:

quicksort :: (Ord a) => [a] -> [a]  
quicksort [] = []  
quicksort (x:xs) =   
    let smallerSorted = quicksort [a | a <- xs, a <= x]  
        biggerSorted = quicksort [a | a <- xs, a > x]  
    in  smallerSorted ++ [x] ++ biggerSorted

Can you please help me find it why it doesn't work with where?

Upvotes: 2

Views: 366

Answers (2)

shang
shang

Reputation: 24802

As an addendum to cldy's answer, note that you can also format where-clauses like this:

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = smaller ++ [x] ++ bigger where
    smaller = quicksort [a | a <- xs, a <= x]
    bigger = quicksort [a |a <- xs, a > x]

I personally prefer this as it conserves some horizontal space, and because most editors can't intelligently auto-indent to the correct column when using the more traditional style.

Upvotes: 3

Mariy
Mariy

Reputation: 5914

That's the whitespace rule. Your definitions after where have to be at the same whitespace indentation. This will compile:

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = smaller ++ [x] ++ bigger
    where smaller = quicksort [a | a <- xs, a <= x]
          bigger = quicksort [a |a <- xs, a > x]

You may want to read this.

Upvotes: 7

Related Questions