公開的函式把函式作為引數

2021-09-08 22:47:50 字數 1921 閱讀 3189

公開的函式把函式作為引數

假設想公開把其它的函式作為引數的函式。最好的方法是用託付(delegate)。

考慮以下的樣例。定義了兩個函式,乙個是公開函式,還有乙個把函式公開為託付。

module strangelights.demomoduleopen system

/// a function that provides filtering

let filterstringlist f ra =

ra |>seq.filter f

// another function that provides filtering

let filterstringlistdelegate (pred:predicate) ra =

let f x =pred.invoke(x)

newresizearray(ra |> seq.filter f)

儘管,filterstringlist 要比 filterstringlistdelegate 短非常多,可是,庫使用者會感謝你為把函式公開為託付而付出的努力。當從 c# 中呼叫這個函式時,就能更加清晰地體會到為什麼這樣。

以下的樣例演示了呼叫filterstringlist。

呼叫這個函式。你須要建立託付,然後,使用funcconvert 類把它轉換成fastfunc,這是一種 f# 型別。用來表示函式值。對於庫使用者來說。另一件相當討厭的事情,須要依賴於fsharp.core.dll。而使用者可能並不想用它。

// !!! c# source !!!

using system;

usingsystem.collections.generic;

usingstrangelights;

usingmicrosoft.fsharp.core;

class maponeclass);

// define a predicate delegate/function

converter pred =

delegate(string s) ;

// convert to a fastfunc

fastfunc ff =

funcconvert.tofastfunc(pred);

// call the f# demo function

ienumerable results =

demomodule.filterstringlist(ff, names);

// write the results to the console

foreach (var name inresults) }}

演示樣例的執行結果例如以下:

stefany

sebastien

如今。把它與呼叫filterstringlistdelegate 函式進行對照,在以下的樣例中展示。由於已經使用了託付,就能夠使用 c# 的匿名託付功能,並把託付直接嵌入函式呼叫中,降低了庫使用者的工作量,且不須要對fsharp.core.dll 的編譯時依賴。

// !!! c# source !!!

using system;

usingsystem.collections.generic;

usingstrangelights;

class maptwoclass);

// call the f# demo function passing in an

// anonymous delegate

list results =

demomodule.filterstringlistdelegate(

delegate(string s) , names);

// write the results to the console

foreach (var s inresults) }}

演示樣例的執行結果例如以下:

aurelie

python把函式作為引數

在2.1小節中,我們講了高階函式的概念,並編寫了乙個簡單的高階函式 def add x,y,f return f x f y print add 5,9,abs 14根據函式的定義,函式執行的 實際上是 abs 5 abs 9 由於引數 x,y 和 f 都可以任意傳入,如果 f 傳入其他函式,就可以...

python 把函式作為引數 高階函式

在實際使用中,我們有時希望將函式作為引數傳遞給另乙個方法使用。比如裝飾器實際就是函式呼叫函式 使用函式當做入參 那就可以把方法名a當做入參傳遞給方法b,呼叫的時候直接用 方法名 來呼叫方法內容 import time def run func print time.strftime y m d h ...

JS 把函式作為引數傳遞

昨天同事問了我乙個挺有意思的問題,就是js如何把函式當作引數傳進另乙個函式中執行,上網找了乙個並做乙個總結,目前我能理解並正常使用的兩種方法 方法一 func 方法名 str 引數 function test1 func,str else function test2 str 方法二 functio...