简体   繁体   中英

Haskell function that alternatively applies input unary functions

I am trying to write a Haskell function that takes two unary functions (f and g) and a list of numbers (ns) and alternatively applies those input functions f and g to the elements of the inputted list.

For example:

func double square [2, 3, 4, 5, 6]

would return

[4, 9, 8, 25, 12]

I am using WinGHCi for my compiler. Any help on writing this function would be appreciated, thanks.

If you don't want to use any library functions, you can do this by using recursion:

func _ _ []     = []
func f g (x:xs) = f x : func g f xs

Expanding on @luqui's comment:

func f1 f2 l = zipWith ($) (cycle [f1, f2]) l

If you don't want to use library functions, just look up their implementations, they're quite simple.

Just a simple solution...

fun :: (a -> b) -> (a -> b) -> [a] -> [b]
fun f g = reverse . snd . foldl step (0,[])
          where
             step (c,ac) x = (c + 1, (if even c then f x else g x) : ac)

Since you do not want to use library functions, you can reproduce the same result without using foldl . The idea is simple to use a counter to know which position is even or not.

Edit: I've made a little confusion on my accumulator. Now, it is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM