Haskell 模式匹配问题

发布于 2024-11-14 11:19:36 字数 573 浏览 2 评论 0原文

当前代码

嗨,我有一个这样的函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

要走干脆点 2024-11-21 11:19:36

当然你只想要 map:

jj::[Int]->[Int]
jj xs = map (`mod` 2) xs

由于柯里化

map (`mod` 2) :: [Int] -> [Int]

正是我们想要的函数,所以我们可以这样做:

jj::[Int]->[Int]
jj = map (`mod` 2)

两者都会产生:

*Main> jj [2,4,5,6,8,9]
[0,0,1,0,0,1]

Surely you just want map:

jj::[Int]->[Int]
jj xs = map (`mod` 2) xs

Due to currying

map (`mod` 2) :: [Int] -> [Int]

is exactly the function we want, so we can just do:

jj::[Int]->[Int]
jj = map (`mod` 2)

Both yield:

*Main> jj [2,4,5,6,8,9]
[0,0,1,0,0,1]
小…红帽 2024-11-21 11:19:36

如果您想要 [] 语法(又名列表理解),您可以说它

jj::[Int]->[Int]
jj xs = [x `mod` 2 | x<-xs]

相当于 MGwynne 的 map 解决方案。

If you want the [] syntax (aka. the list comprehension), you can say

jj::[Int]->[Int]
jj xs = [x `mod` 2 | x<-xs]

which is equivalent to MGwynne's map solution.

苏璃陌 2024-11-21 11:19:36

查看以下函数:

map :: (a -> b) -> [a] -> [b]
fmap :: (Functor f) => (a -> b) -> f a -> f b

其中列表是类型类仿函数的实例。您需要一个 Int 类型的函数 -> Int 进行转换。

jj :: (Functor f, Integral i) => f i -> f i
jj = fmap (`mod` 2)

(对于列表,mapfmap 执行相同的操作。fmapmap 的泛化)

Look at the following functions:

map :: (a -> b) -> [a] -> [b]
fmap :: (Functor f) => (a -> b) -> f a -> f b

where a list is an instance of the typeclass functor. You'll need a function of type Int -> Int that does your transformation.

jj :: (Functor f, Integral i) => f i -> f i
jj = fmap (`mod` 2)

(For lists, both map and fmap do the same thing. fmap is a generalization of map)

篱下浅笙歌 2024-11-21 11:19:36

递归方式:

dividablelist :: [Int] -> [Int]
dividablelist [] = []
dividablelist (x:xs) = mod x 2 : dividablelist xs

The recursive way:

dividablelist :: [Int] -> [Int]
dividablelist [] = []
dividablelist (x:xs) = mod x 2 : dividablelist xs
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文