【问题标题】:What are functors, and why do we need them?什么是函子,我们为什么需要它们?
【发布时间】:2016-06-09 12:49:12
【问题描述】:

我不明白 Factor 的 functors。我想首先了解什么是“函子”会有所帮助。

谷歌说:

一个函数;一个运算符。

在Factor中,所有函数(词)都是运算符,并且是一等的。 (事实上​​,我对不是头等舱的因素想不到太多)。这个定义不是很有帮助。

维基百科说:

函子可以指:

  • ...
  • 在计算机编程方面:
    • 函数对象用于传递函数指针及其状态
    • ...
    • 在 Haskell 中,Functor 描述了执行映射操作的函数的泛化

“功能对象”的页面说:

像普通函数一样被调用或调用的对象,通常使用相同的语法(函数参数也可以是函数)。

所以函子是一等函数?这没什么特别的,反正文字和语录之类的东西在Factor中已经是一流的了。

Factor Functor 有奇怪的语法,让我想起了泛型之类的东西。

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

关于这些的文档非常稀少。这些是什么?我应该什么时候使用它们?

【问题讨论】:

    标签: functor factor-lang


    【解决方案1】:

    不要把函子想成'They're named "functors" to annoy category theory fanboys and language purists.' :)

    它们的用途主要是生成样板代码或模板代码。就像 C++ 模板是一种优化功能一样,因为泛型调度可能很慢,Factor 函子也是如此。

    这里的例子:

    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,Factor 将为您创建单词clear-personinit-personperson-datasource

    什么时候使用它们?我认为永远不会,除非您遇到需要使用它们的性能问题。它们对grepability 非常不利。

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 2017-02-24
      • 2011-08-19
      • 1970-01-01
      • 2017-12-27
      • 2017-08-24
      • 2023-03-04
      相关资源
      最近更新 更多