haskell - Mapping a function on chained pairs of elements from a list -


i want map function on chained pairs of elements list. consider list:

a = [1,2,3,4,5] 

by using e.g. function f a1 a2 = a1 < a2, want get:

[true,true,true,true] 

the following seems work in general:

zipwith f (tail a) 

however, find kind of hackish. there more appropriate way, maybe using fold?

i think can speak on behalf of haskell community if tell that the idiomatic way of doing in haskell. hack using fold not readable first variant:

f p xs = snd $ foldl (\acc x -> (x, snd acc ++ [p (fst acc) x])) (head xs, []) (tail xs) 

thank @willness supplying more readable version of above's function, although still not beat zipwith in brevity , clarity.

f p = foldr g [] . tails g (x:y:_) r = p x y:r; g _ _ = [] 

this hackish. problem using fold in situation elements dealt separately , not "know" neighbours. values know accumulator , own.

in example, doing f (<) [1,2,3,4,5] check if left element of pair smaller 1 before, way less readable doing:

f p xs = zipwith p xs (tail xs) 

usage same above.


note no professional in haskell language, may approach using fold have been written in better way, nevertheless never beat elegance of zipwith approach.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -