什么是这种功能性“模式”叫什么名字? [英] What is this functional "pattern" called?

查看:197
本文介绍了什么是这种功能性“模式”叫什么名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到这个函数的需求时,我正在玩弄一些函数式编程,但是我不知道标准命名法中这种东西被称为什么。
任何人都知道它吗?

$ p $ 函数WhatAmIDoing(args ...)
返回函数()
返回参数
结束
结束

编辑: strong>泛化函数,它需要一个可变数量的参数(或者可能是一个隐式列表),并返回一个函数,当被调用时返回所有的参数,如咖喱或泡菜,但它似乎不是。 / p>

解决方案

WhatAmIDoing是高阶函数,因为它是一个返回另一个函数的函数。



它返回的是一个 thunk —为延迟计算实际值而创建的闭包。通常创建thunk是为了懒惰地评估一个表达式(并可能记住它),但在其他情况下,只需要一个函数来代替裸值,就像常常是5 ,它在某些语言中返回一个总是返回5的函数。



后者可能适用于给定的示例,因为假设语言是以应用程序 - 顺序(即在调用函数之前计算参数),该函数没有其他目的,只能将值转换为返回它们的函数。



WhatAmIDoing实际上是一个实现我描述的不断功能。但是一般情况下,你不必在内部函数中返回 args 。您可能会返回 ackermann(args),这可能需要很长时间,如...



<$ p
返回ackermann(args)
结束
结束
函数WhatAmIDoing2(args ...)
返回函数code>

但是WhatAmIDoing2会立即返回,因为ackermann函数的评估将暂停在 closure 。 (是的,即使是按照价值的语言。)


I was fooling around with some functional programming when I came across the need for this function, however I don't know what this sort of thing is called in standard nomenclature. Anyone recognizes it?

function WhatAmIDoing(args...)
   return function()
       return args
   end
end

Edit: generalized the function, it takes a variable amount of arguments ( or perhaps an implicit list) and returns a function that when invoked returns all the args, something like a curry or pickle, but it doesn't seem to be either.

解决方案

WhatAmIDoing is a higher-order function because it is a function that returns another function.

The thing that it returns is a thunk — a closure created for delayed computation of the actual value. Usually thunks are created to lazily evaluate an expression (and possibly memoize it), but in other cases, a function is simply needed in place of a bare value, as in the case of "constantly 5", which in some languages returns a function that always returns 5.

The latter might apply in the example given, because assuming the language evaluates in applicative-order (i.e. evaluates arguments before calling a function), the function serves no other purpose than to turn the values into a function that returns them.

WhatAmIDoing is really an implementation of the "constantly" function I was describing. But in general, you don't have to return just args in the inner function. You could return "ackermann(args)", which could take a long time, as in...

function WhatAmIDoing2(args...)
   return function()
       return ackermann(args)
   end
end

But WhatAmIDoing2 would return immediately because evaluation of the ackermann function would be suspended in a closure. (Yes, even in a call-by-value language.)

这篇关于什么是这种功能性“模式”叫什么名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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