大多数惯用的`[a

编程入门 行业动态 更新时间:2024-10-26 18:19:24
本文介绍了大多数惯用的`[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

本文发布于:2023-07-24 13:24:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1203703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!