English 中文(简体)
F#:两个界定职能的方法?
原标题:F#: two ways of defining functions?
  • 时间:2011-10-10 07:12:16
  •  标签:
  • f#

这两者相当:

let f(x) =
    10

let g = fun(x) ->
    10

我认为? 它们似乎也一样,但是否有任何情况表明两者的行为会有所不同? 我认为第二版是有用的(即使有更精确的版本),因为你可以使用<代码>和>、<>>>>和<代码><操作者实施假装式腐蚀器型模式;在我携带<>/em>使用第一个版本的情况下,是否有任何操作者?

此外,我完全理解第二个作品(右上的障碍只是功能表达方式,我把这种表述放在了格上),但第一个作品又是如何? 是否有一些汇编者或特殊案例把该辛塔x从简单转让说明转变为功能定义?

最佳回答

正如布赖恩已经回答的那样,两者都是一样的。 返回<代码>fun,而不是通过<代码><>let<>>>/code>宣布职能,如果你想在恢复职能之前做一些事情(即有些初步确定)。

例如,如果你想要创造增加随机数目的职能,你可以写:

let f1 x = 
  let rnd = new System.Random()
  x + rnd.Next()

let f2 = 
  let rnd = new System.Random()
  fun y -> y + rnd.Next()

在此,<代码>f1 创建新的<代码>Random,每次执行,但<代码>f2 采用<代码>rnd的相同实例 所有时间(Sf2)都是编写这一文件的最佳方式。 但是,如果你返回<代码>fun 之后,F#汇编者立即优化了该守则,这两起案件相同。

问题回答

They are equivalent (modulo the value restriction , which allows functions, but not values, to be generic, see e.g. here).





相关问题
F#: Storing and mapping a list of functions

I have a number of events that happen in a game. I want to control the time and order at which these events occur. For example: Event 1: Show some text on screen for N frames & play a sound ...

Creating Silverlight 3 applications with F#

Is there an easy way to create Silverlight 3 applications with F# (October CTP)? I have seen the F# for Silverlight, but that only works with the May CTP. I am using Visual Studio Integrated Shell ...

How To Change List of Chars To String?

In F# I want to transform a list of chars into a string. Consider the following code: let lChars = [ a ; b ; c ] If I simply do lChars.ToString, I get "[ a ; b ; c ]". I m trying to get "abc". I ...

Unzipping ZLIB compressed portions of a binary file

I m reading a file(a flash swf) from .Net 3.5 that has a header which states whether the body of the file/Stream is compressed or not. However, I m having problems-after I rewrap the basic File ...

Pretty print a tree

Let s say I have a binary tree data structure defined as follows type a tree = | Node of a tree * a * a tree | Nil I have an instance of a tree as follows: let x = Node (Node (...

F# String Pattern-Matching with Wildcards

As part of a project I have assigned myself as a way of improving my knowledge of F# and functional programming in general, I am attempting to write a string pattern-matching algorithm from scratch ...