码迷,mamicode.com
首页 > 其他好文 > 详细

公开的函数把函数作为參数

时间:2017-06-19 14:15:30      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:another   new   console   article   style   ima   sof   tracking   module   

公开的函数把函数作为參数

 

假设想公开把其它的函数作为參数的函数。最好的方法是用托付(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<string>) ra =

  let f x =pred.Invoke(x)

  newResizeArray<string>(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{

  public static void MapOne() {

    // define a list of names

   List<string> names = new List<string>(

      new string[] { "Stefany", "Oussama",

  "Sebastien", "Frederik"});

 

    // define a predicate delegate/function

   Converter<string, bool> pred =

      delegate(string s) {return s.StartsWith("S");};

 

    // convert to a FastFunc

   FastFunc<string, bool> ff =

      FuncConvert.ToFastFunc<string,bool>(pred);

 

    // call the F# demo function

   IEnumerable<string> results =

     DemoModule.filterStringList(ff, names);

 

    // write the results to the console

    foreach (var name inresults) {

     Console.WriteLine(name);

    }

  }

}

 

演示样例的执行结果例如以下:

 

Stefany

Sebastien

 

如今。把它与调用filterStringListDelegate 函数进行对照,在以下的样例中展示。由于已经使用了托付,就能够使用 C# 的匿名托付功能,并把托付直接嵌入函数调用中,降低了库用户的工作量,且不须要对FSharp.Core.dll 的编译时依赖。

 

// !!! C# Source !!!

using System;

usingSystem.Collections.Generic;

usingStrangelights;

 

class MapTwoClass{

  public static void MapTwo() {

    // define a list of names

   List<string> names = new List<string>(

      new string[] { "Aurelie", "Fabrice",

    "Ibrahima", "Lionel"});

 

    // call the F# demo function passing in an

    // anonymous delegate

   List<string> results =

     DemoModule.filterStringListDelegate(

      delegate(string s) {return s.StartsWith("A");}, names);

 

    // write the results to the console

    foreach (var s inresults) {

     Console.WriteLine(s);

    }

  }

}

 

演示样例的执行结果例如以下:

 

Aurelie

 

 

公开的函数把函数作为參数

标签:another   new   console   article   style   ima   sof   tracking   module   

原文地址:http://www.cnblogs.com/yangykaifa/p/7048169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!