2016-06-09 208 views
2

我不明白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 

的文檔是這些極其稀少。他們是什麼?我應該什麼時候使用它們?

回答

2

不要以爲仿函數作爲'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-personinit-personperson-datasource你。

何時使用它們?我認爲永遠不會有,除非你有性能問題值得使用。他們對grepability非常不利。

+0

噢,我的天哪,這真的很酷... – cat

相關問題