大多数惯用的`[a - > a] - > (a - > a)` [英] Most idiomatic implementation of `[a -> a] -> (a -> a)`

查看:192
本文介绍了大多数惯用的`[a - > a] - > (a - > a)`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个函数列表,每个类型 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 [] = id

and

foo = foldr (.) id

and

foo = appEndo . mconcat . map Endo

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

解决方案

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.

这篇关于大多数惯用的`[a - > a] - > (a - > a)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆