如何使用"让"用于在Haskell中定义多个变量的关键字

时间:2016-08-05 15:28:11

标签: haskell let

我在Haskell的代码片段下方实现了快速排序算法。

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

然而它不会被GHCI编译并且它告诉第5行有语法错误。但是我已经检查了Haskell的语法&#34;让&#34;关键字似乎没问题。有没有人可以帮我解决这个问题?非常感谢。

3 个答案:

答案 0 :(得分:10)

您需要缩进let表达式,因为它是前一行的延续。

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

答案 1 :(得分:2)

执行此操作的另一种方法您可以使用花括号和分号{ ; ; ; }在一行中编写它:

quicksort (x:xs) = let {smaller = quicksort [a | a <- xs, a <= x]; bigger = quicksort [a | a <- xs, a > x]} in smaller ++ [x] ++ bigger

答案 2 :(得分:-3)

看看这个。一个可能有用的例子:

let (a, b, c) = (1, 2, 3) 在“代码的其余部分”

以您的示例为例:

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