I've the below code snippet in Haskell to implement the quicksort algorithm.
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smaller = quicksort [a | a <- xs, a <= x]
bigger = quicksort [a | a <- xs, a > x]
in smaller ++ [x] ++ bigger
However, GHCi rejects the program telling me that line 5 has a syntax error. But I've checked the Haskell syntax for the "let" keyword and it seems OK.
Is there anyone who can help me with this problem? Thanks a lot.
It is important to know that let ... in ... is an expression, that is, it can be written wherever expressions are allowed. In contrast, where is bound to a surrounding syntactic construct, like the pattern matching line of a function definition.
We first note that variables in Haskell can only be assigned once, unlike in many imperative programming languages, where a variable can be overwritten with different values arbitrarily many times.
The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.
You need to indent the let
expression, since it is a continuation of the previous line.
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smaller = quicksort [a | a <- xs, a <= x]
bigger = quicksort [a | a <- xs, a > x]
in smaller ++ [x] ++ bigger
Another way to do this You can write it in one line using braces and semicolons { ; ; ; }
:
quicksort (x:xs) = let {smaller = quicksort [a | a <- xs, a <= x]; bigger = quicksort [a | a <- xs, a > x]} in smaller ++ [x] ++ bigger
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With