【发布时间】:2019-09-04 13:52:33
【问题描述】:
我正在用 haskell 做一些练习。我的任务是从列表[0..10] 中创建一个不带 0 的偶数平方列表。
我已经使用 Haskell 中的列表理解实现了它(查看下面的代码块。)但现在我的任务是使用函数 map 和 filter 来实现它。
List comprehension in Haskell:
[x^2 | x <- [0..10], mod x 2==0, x/=0]
f = (\x -> (x^2))
p = (\x -> mod x 2 == 0 && x/=0)
map1 :: (a->b) -> [a] -> [b]
map1 f [] = []
map1 f (x:xs) = f x : map1 f xs
filter1 :: (a -> Bool) -> [a] -> [a]
filter1 p [] = []
filter1 p (x:xs)
| p x = x:filter p xs
| otherwise = filter1 p xs
我实现了map 和filter 函数(我知道这是多余的,但它实践了我)并且我有一个平方函数。现在的问题是将map 与filter 结合起来,我还在p = (\x -> mod x 3 == 0 && x/=0) 收到error 消息。
我的错误信息是<interactive>:4:1: error: Variable not in scope : p :: Integer -> t
【问题讨论】:
-
您收到什么错误信息?
p的定义在 GHCi 中对我来说很好。 -
至于如何使用
map和filter来获得与您的列表理解相同的结果-您尝试过哪种组合?你知道map和filter应用于哪些函数吗? -
@RobinZigmond 我的错误信息是
:4:1: error: Variable not in scope : p :: Integer -> t -
@RobinZigmond 我没有尝试太多,但这是我使用 Haskell 的第二天,我有点不知所措。
-
我不建议尝试在交互式会话中完成所有这些操作。我认为这最终是您超出范围错误的原因。尝试将定义移动到文件中并使用
:l将其加载到 GHCi 中
标签: list haskell filter higher-order-functions map-function