在Haskell中将函数从LET迁移到WHERE

时间:2012-11-25 15:43:20

标签: haskell

为了提高我的Haskell技能,我决定通过一些示例代码尝试以不同的方式重写。

这是初始功能:

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  

以下是迁移的功能:

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]  

然而,我认为它不起作用。 有什么不对?使用LET的函数可以移植到WHERE吗?

这是我的错误输出:

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

非常感谢!

1 个答案:

答案 0 :(得分:14)

您需要匹配where子句中表达式的缩进,例如

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]  

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]