开发者

Haskell Pattern Matching Problem

Current Code

Hi I have a function like this:

jj::[Int]->[Int]
j开发者_运维百科j 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]


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]


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.


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)


The recursive way:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜