3

为了提高我的 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.

非常感谢!

4

1 回答 1

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]  
于 2012-11-25T15:49:06.837 回答