Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Check if position is even/odd

Tags:

haskell

What I need to do is to apply alternately 2 functions in a list. For example:

(*2) (-3) [4,5,6,7,8]

would result in

[8,2,12,4,16], because 4*2, 5-3, 6*2, 7-3, 8*2...

What I was thinking was

funct :: (a -> b) -> (a -> b) -> [a] -> [b]

and then something like

[f x | x <- xs] however I won't have just "f", but will have the other function as well.

So I was thinking about checking the position of x. If it is an even position, then f x. Otherwise g x.

Could someone help me?

Tks.

like image 436
frederico s Avatar asked Dec 14 '22 07:12

frederico s


1 Answers

You do not really need the index, what you need is a list that alternates between (*2) and (-3). We can make use of cycle :: [a] -> [a] and zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]. We can thus use:

zipWith ($) (cycle [(2*), subtract 3]) [4,5,6,7,8]

Here ($) :: (a -> b) -> a -> b is used to perform a function application. So ($) f x is equivalent to f x.

This gives the expected:

Prelude> zipWith ($) (cycle [(2*), subtract 3]) [4,5,6,7,8]
[8,2,12,4,16]
like image 65
Willem Van Onsem Avatar answered Jan 02 '23 17:01

Willem Van Onsem