Haskell 模式匹配问题
当前代码
嗨,我有一个这样的函数:
jj::[Int]->[Int]
jj xs = [x|x<-xs,x `mod` 2 ==0]
对于输入 [1..20]
,它给我作为输出 :
[2,4,6,8,10,12,14,16,18,20] -> only the values divisible by 2
我需要什么
如果列表值可被 2 整除,则将其解释为 0
,否则解释为 1
:
输入< /强>: [243,232,243]
输出:[1,0,1]
Current Code
Hi I have a function like this:
jj::[Int]->[Int]
jj xs = [x|x<-xs,x `mod` 2 ==0]
For the input [1..20]
it gives me as output :
[2,4,6,8,10,12,14,16,18,20] -> only the values divisible by 2
What I require
If list value is dividable by 2, it is interpreted as 0
and otherwise as 1
:
Input : [243,232,243]
Output : [1,0,1]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然你只想要 map:
由于柯里化
正是我们想要的函数,所以我们可以这样做:
两者都会产生:
Surely you just want map:
Due to currying
is exactly the function we want, so we can just do:
Both yield:
如果您想要 [] 语法(又名列表理解),您可以说它
相当于 MGwynne 的
map
解决方案。If you want the [] syntax (aka. the list comprehension), you can say
which is equivalent to MGwynne's
map
solution.查看以下函数:
其中列表是类型类仿函数的实例。您需要一个 Int 类型的函数 -> Int 进行转换。
(对于列表,
map
和fmap
执行相同的操作。fmap
是map
的泛化)Look at the following functions:
where a list is an instance of the typeclass functor. You'll need a function of type
Int -> Int
that does your transformation.(For lists, both
map
andfmap
do the same thing.fmap
is a generalization ofmap
)递归方式:
The recursive way: