Nicholas
Nicholas

Reputation: 135

Dividing evens of a list by two

halveEvens :: [Int] -> [Int] 
halveEvens xs = [if xs == even then 'div' 2 xs | x<-xs]

Hey I'm trying to write down some code in haskell which will take the evens from a list and divide them by two. I am really new to this, so I am having some trouble. Is there anyone who could put me on the right track? I want to achieve this using list comprehension!

Upvotes: 0

Views: 832

Answers (2)

jev
jev

Reputation: 2013

Using list comprehension with a guard after a comma:

halveEvens xs = [x `div` 2 | x<-xs, even x]

You could read it as a mathematical definition: take all x values from xs that are even, and collect the result of dividing them into a list. In ghci you can use :t to check the types and make them match (xs is of type [Int], x is Int, and even is (Integral a) => a -> Bool).

Upvotes: 0

andrybak
andrybak

Reputation: 2349

In your function xs is a list, even is a function that checks if Integral is even.

To use functions like operators, you enclose it in back quotes like this : x `div` 2.

halveEvens :: [Int] -> [Int]
halveEvens = map halveOneEven

halveOneEven :: Int -> Int
halveOneEven x = if (even x) then (x `div` 2) else x

Upvotes: 3

Related Questions