Reputation: 16184
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]
Upvotes: 1
Views: 428
Reputation: 13002
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
)
Upvotes: 3
Reputation: 21
The recursive way:
dividablelist :: [Int] -> [Int]
dividablelist [] = []
dividablelist (x:xs) = mod x 2 : dividablelist xs
Upvotes: 2
Reputation: 654
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.
Upvotes: 4
Reputation: 3522
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]
Upvotes: 5