11

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Lyndon
  • 111
  • 1
  • 1
  • 3
  • because `let` cannot be in the same column as your function's, in this case column 1. just add a space in the beginning of lines starting 5. – Jason Hu Aug 05 '16 at 15:30
  • A bit unreladely to your question, but it could help you somehow if you are learning haskell: Note that this algorithm is not really quicksort. It doesn't use constant memory. http://augustss.blogspot.cz/2007/08/quicksort-in-haskell-quicksort-is.html – user1747134 Aug 05 '16 at 16:10
  • @user1747134 also [this](https://stackoverflow.com/q/14786904/849891) and its links. – Will Ness Jan 07 '20 at 16:14

3 Answers3

20

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
chepner
  • 497,756
  • 71
  • 530
  • 681
2

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

Will Ness
  • 70,110
  • 9
  • 98
  • 181
-2

Check this out. An example that may be useful:

let (a, b, c) = (1, 2, 3) in "The Rest of the Code"

On your example:

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
    let (smaller, bigger) = ( quicksort [a | a <- xs, a <= x]
                            , quicksort [a | a <- xs, a >  x]) 
    in  smaller ++ [x] ++ bigger
Will Ness
  • 70,110
  • 9
  • 98
  • 181
Samuel
  • 11
  • 1
  • I don't see how this is related to the question, can you elaborate? – Noughtmare Jun 11 '21 at 10:29
  • My mistake. I had errors. It was edited and resolved – Samuel Jun 12 '21 at 17:47
  • Ah, now I understand. You are showing how to bind multiple variables in one binding, which is what the title of the question seems to ask, but after reading the description, I think that the asker is not really looking for that. Also, please format your code, see https://stackoverflow.com/editing-help#syntax-highlighting. – Noughtmare Jun 12 '21 at 18:08