如果我有一个函数列表,每个类型 a - >一个类型的,结合它们的最短,最优雅和最习惯的方式是什么?最好不添加额外的依赖项?
一些变体包括: $ $ $ $ $ $ $ $ $ x:xs)= x。 (foo xs) foo [] = id
和
foo = foldr(。)id和
foo = appEndo。 mconcat。 map Endo但由于某种原因,我期望找到更好的东西。
解决方案我会说你不会击败
comp = foldr(。)id为什么?那么我们有一个列表,我们试图以正确的关联方式来减少它。
如果您查看和的实现, sum ,最大值以及类似的,你会发现这是它们在标准库中的实现方式,我认为你不会比这更习惯于使用它:)
切线:我不愿意添加注释中提到的 foldr1 变体,因为我会说这是意外行为不是说最大值,这显然是必须的。
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 [] = idand
foo = foldr (.) idand
foo = appEndo . mconcat . map Endobut for some reason I’m expecting to find something nicer.
解决方案I'd say you're not going to beat
comp = foldr (.) idWhy? 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.
更多推荐
大多数惯用的`[a
发布评论