3

In order to improve my Haskell skills I decided to go through some example code and try to rewrite in a different way.

Here is the initial function:

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  

Here is the migrated function:

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

However looks to me that it is not working. Is there something wrong? Can functions using LET ported to WHERE?

This is my error output:

/Users/graph/Documents/Uni/Haskell/hey.hs:43:5:
    parse error on input `biggerSorted'
Failed, modules loaded: none.

Many thanks!

1
  • 5
    In general when asking for help you should say why you think it is not working. If the code does not compile, you should paste in the error message. If the code generates the wrong output, you should give us example input and output, and also tell us what you think the output should be instead. Commented Nov 25, 2012 at 15:52

1 Answer 1

14

You need to match the indentation of the expressions in a where clause, e.g.

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

or

quicksort :: (Ord a) => [a] -> [a]  
quicksort [] = []  
quicksort (x:xs) = smallerSorted ++ [x] ++ biggerSorted 
    where
        smallerSorted = quicksort [a | a <- xs, a <= x]  
        biggerSorted = quicksort [a | a <- xs, a > x]  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.