F#第四课:F#中的值,方法和属性

1. Simple values: Functions, parameters, and top-level items defined using let or pattern matching.

Examples: form, text, wordCount.

简单值:函数,参数和顶层成员定义都使用let或模式匹配来实现。

代码
let form = new Form()

let highLow a b =
    
match (a,b) with
    
| ("lo", lo), ("hi", hi) -> (lo,hi)
    
| ("hi", hi), ("lo", lo) -> (lo,hi)

2. Methods: Function values associated with types. Interfaces, classes, and record and union types can all have associated methods. Methods can be overloaded (see Chapter 6) and must be applied immediately to their arguments.

Examples: System.Net.WebRequest.Create and resp.GetResponseStream.

方法:类型相关的函数值。接口,类和记录,还有union类型都可以有与之相关的方法。方法可以重载,并且必须赋予它们参数。


3. Properties: A shorthand for invoking method members that read or write underlying data. Interfaces, classes, and record and union types can all have associated properties. Examples: System.DateTime.Now and form.TopMost.

属性:一个调用成员函数的快捷方式用于读写值。接口,类和记录,还有union类型都可以有与之相关联的属性。我们可以使用<-操作符来赋值。

代码
Form.Text <- "form1"

 

4. Indexer properties: A property can take arguments, in which case it is an  indexer property. Indexer properties named Item can be accessed using the .[_] syntax. Examples: vector.[3] and matrix.[3,4].

属性索引器:带参数的属性,在这里它是一个属性索引器。访问命名的属性索引器可以使用.[_]。

 

另外今天遇到了一个麻烦问题,就是如何利用F#来进行数列求和。比如输入一个值100,求数列1到100和,如果我们用C/C++的语言来写 

代码
int Accumulate(int n)
{
    
int result = 0;
    
for (int i=0; i<n; i++)
    {
       result 
= result + i;
    }

    
return result;
}

如果这段代码直接翻译成F#程序的话,看起来是这样

代码
let Accumulate(n:int) =
  
let mutable result = 0
  
let mutable i = n
  
while i > 0 do 
    result 
<- result + i
    i 
<- i - 1
  (result)

 但是我们在F#中不提倡使用mutable这样的可变变量,所以比较好的方法是使用递归函数

代码
let rec Accumulate1(n:int) =
    
if n <= 1 then 1 else n + Accumulate1(n-1)

至于更优化的方式,暂时还没想到。

posted @ 2009-11-29 18:16  moonz-wu  阅读(328)  评论(1编辑  收藏  举报