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 f开发者_运维问答ollowing 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
?
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.
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.
精彩评论