Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

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

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 without adding extra dependencies?

Some variants include

foo (x:xs) = x . (foo xs)
foo [] = id

and

foo = foldr (.) id

and

foo = appEndo . mconcat . map Endo

but for some reason I’m expecting to find something nicer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...