咖喱减法 [英] Currying subtraction

查看:96
本文介绍了咖喱减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们想映射一个将范围的每个元素增加1的函数,我们可以写

If we want to map a function that increases every element of a range by 1, we could write

map (\x -> x + 1) [1..5]

但我想大多数人会只需去

but I guess most people would just go for

map (+1) [1..5]

。但是这显然不适用于(-1),因为那是负的。

instead. But this obviously doesn't work with (-1) since that's negative one.

所以,第一件事是

map (+(-1)) [1..5]

这将有助于考虑如何在前奏中定义减法( x - y = x + negate y ),但看起来有点奇怪我。然后我想出了

which would make sense considering how subtraction is defined in the Prelude (x - y = x + negate y), but looks a bit odd to me. I then I came up with

map (flip (-) 1) [1..5]

这对我来说看起来更好,但也许有点太复杂了。

This somehow looks better to me, but is maybe a bit too complicated.

现在我知道这没有什么大不了,但我想知道我是否错过了一个更明显的方式来写这个?如果不是,你喜欢哪种方式?我真的只是问,因为经常是这样的小细节,使你的代码更加惯用,因此对于其他开发人员阅读它是愉快的。

Now I know this no big deal, but I'm wondering if I'm missing a more obvious way to write this? If not, which of the 2 ways would you prefer? I'm really just asking because often it's small details like this that make your code more idiomatic and hence pleasant for other developers who have to read it.

解决方案

现在我有几个答案,个人最爱是

Now that I got a couple of answers, I think my personal favorite is

map (subtract 1) [1..5]

后跟

map pred [1..5]

主要是因为第一个是显式的,没有人需要猜测/查找 pred 表示(前导)。

mostly because the first one is really explicit and nobody needs to guess/look up what pred means (predecessor).

推荐答案

您可以使用减号函数代替<$ c $

You can use the subtract function instead of - if you want to right-section subtraction:

map (subtract 1) [1..5]

这篇关于咖喱减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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