什么是仿函数,为什么我们需要它们?
问题描述:
我不明白Factor的functors。我想这将有助于首先了解“仿函数”是什么。什么是仿函数,为什么我们需要它们?
谷歌表示:
的功能;一位操作员。
在因素中,所有函数(单词)都是运算符,并且都是一流的。 (事实上,我不能想到很多因素,不是头等舱)。这个定义并没有那么有用。
维基说:
功能概括为函子可参考:
- ...
- 在计算机程序设计:用来传递函数指针
- 函数对象连同其状态
- ...
- 在Haskell算符描述的执行映射操作
“函数对象” 的网页显示:
一个对象被调用或调用,就好像它是一个普通的函数,通常使用相同的语法(函数参数也可以是一个函数)。
所以一个仿函数是一流的函数吗?这没什么特别的,无论如何,单词和引语以及其他东西已经在Factor中名列前茅。
因子函子有奇怪的语法,让我想起泛型或什么。
resource:unmaintained/models/combinators/templates/templates.factor:
FROM: models.combinators => <collection> #1 ;
FUNCTOR: fmaps (W --)
W IS ${W}
w-n DEFINES ${W}-n
w-2 DEFINES 2${W}
w-3 DEFINES 3${W}
w-4 DEFINES 4${W}
w-n* DEFINES ${W}-n*
w-2* DEFINES 2${W}*
w-3* DEFINES 3${W}*
w-4* DEFINES 4${W}*
WHERE
MACRO: w-n (int -- quot) dup '[ [ _ narray <collection> ] dip [ _ firstn ] prepend W ] ;
: w-2 (a b quot -- mapped) 2 w-n ; inline
: w-3 (a b c quot -- mapped) 3 w-n ; inline
: w-4 (a b c d quot -- mapped) 4 w-n ; inline
MACRO: w-n* (int -- quot) dup '[ [ _ narray <collection> #1 ] dip [ _ firstn ] prepend W ] ;
: w-2* (a b quot -- mapped) 2 w-n* ; inline
: w-3* (a b c quot -- mapped) 3 w-n* ; inline
: w-4* (a b c d quot -- mapped) 4 w-n* ; inline
;FUNCTOR
的文档是这些极其稀少。他们是什么?我应该什么时候使用它们?
答
不要以为仿函数作为'They're named "functors" to annoy category theory fanboys and language purists.' :)
它们的使用主要是为了产生样板或模板代码。就像C++模板是一个优化功能一样,因为通用调度可能很慢,因子函数也是如此。
这里举例:
USING: functors io lexer namespaces ;
IN: examples.functors
FUNCTOR: define-table (NAME --)
name-datasource DEFINES-CLASS ${NAME}-datasource
clear-name DEFINES clear-${NAME}
init-name DEFINES init-${NAME}
WHERE
SINGLETON: name-datasource
: clear-name (--) "clear table code here" print ;
: init-name (--) "init table code here" print ;
name-datasource [ "hello-hello" ] initialize
;FUNCTOR
SYNTAX: SQL-TABLE: scan-token define-table ;
现在,您可以编写SQL-TABLE: person
和因素将创建话clear-person
,init-person
和person-datasource
你。
何时使用它们?我认为永远不会有,除非你有性能问题值得使用。他们对grepability非常不利。
噢,我的天哪,这真的很酷... – cat