gpt4 book ai didi

haskell - Haskell 中将函数从 LET 迁移到 WHERE

转载 作者:行者123 更新时间:2023-12-02 16:02:54 26 4
gpt4 key购买 nike

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

非常感谢!

最佳答案

您需要匹配 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]

关于haskell - Haskell 中将函数从 LET 迁移到 WHERE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com