呼叫委派与部分功能应用程序(Call delegation vs partial function application)

编程入门 行业动态 更新时间:2024-10-14 20:25:53
呼叫委派与部分功能应用程序(Call delegation vs partial function application)

我需要从我的代码中的许多地方调用一个带有两个参数的函数。

hash(itemToHash, algorithm) { ... }

我不想在每个函数调用中传递algorithm参数。

我可以使用一个可以委托调用的参数创建一个函数:

md5hash(itemToHash) { hash(itemToHash, 'md5') }

或者我可以使用部分应用程序来绑定algorithm参数。

我将这样做的方法是创建一个更高阶函数,返回部分应用的哈希函数,我会从代码中的许多地方调用这个更高阶函数来获得单个参数函数。

但是,这不是不必要的复杂吗? 与简单的呼叫授权相比,我认为第二种方法没有任何好处。

I need to call a function with two parameters from many places in my code.

hash(itemToHash, algorithm) { ... }

I don't want to pass the algorithm parameter in each of the function calls.

I could create a function with one parameter that would delegate the call:

md5hash(itemToHash) { hash(itemToHash, 'md5') }

Or I could use partial application to bind the algorithm parameter.

The way I would go about this would be to create a higher order function that returns the partially applied hash function and I would call this higher order function from many places in the code to get the single parameter function.

However, isn't that unnecessary complicated? I don't really see any benefit in the second approach compared to simple call delegation.

最满意答案

假设你有一些函数partial ,它将参数partial地应用于其他函数。 您不需要在代码中的任何位置调用此partial函数,以便使用部分应用的函数。

实际上你只需要调用一次。 要生成部分应用的函数然后说,将其绑定到名称。

md5Hash := partialRight(hash, 'md5')

至于我的理解甚至

md5Hash(itemToHash) { hash(itemToHash, 'md5') }

是某种部分应用。 虽然是静态的。 partial函数的好处是能够在运行时创建部分应用的函数。

Say you have some function partial that partially applies arguments to other functions. You don't need to call this partial function everywhere in your code that want to make use of the partially applied function.

In fact you have to call it only once. To generate a partially applied function and then say, bind it to a name.

md5Hash := partialRight(hash, 'md5')

As for my understanding even

md5Hash(itemToHash) { hash(itemToHash, 'md5') }

is some kind of partial application. Albeit a static one. The benefit of a partial function is the ability to create partially applied functions at runtime.

更多推荐

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

发布评论

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

>www.elefans.com

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