Most idiomatic implementation of `[a -> a] -> (a -> a)`

前端 未结 2 648
陌清茗
陌清茗 2020-12-19 13:46

If I have a list of functions, each of the type a -> a for some type, what is the most shortest, elegant and idiomatic way to combine them; preferably withou

2条回答
  •  醉话见心
    2020-12-19 14:47

    I'd say you're not going to beat

    comp = foldr (.) id
    

    Why? Well we have a list of things and we're trying to reduce it in a right associative way.

    If you look at the implementations of and, sum, maximum and similar, you'll see that this is how they're implemented in the standard library, I don't think you get more idiomatic than that :)

    Tangent: I hesitate to add the foldr1 variant mentioned in comments because I'd say that it's unexpected behavior for this to be partial, unlike say maximum where it clearly must be.

提交回复
热议问题