F#教程(一)

// This sample will guide you through elements of the F# language.  这个示例将会指导你通过F#语言的元素
//
// *******************************************************************************************************
//   为了交互执行F#代码,可以选择部分代码并按下Alt+回车,To execute the code in F# Interactive, highlight a section of code and press Alt-Enter or right-click
//   或者点击右键选择“交互执行”。你可以在“视图”菜单打开F#交互窗口and select "Execute in Interactive".  You can open the F# Interactive Window from the "View" menu.
// *******************************************************************************************************
//
// 更多关于F#的,请看:For more about F#, see:
//     http://fsharp.org
//
// 若要使用 F # 的其他模板,请参阅在 Visual Studio 中的在线模板For additional templates to use with F#, see the 'Online Templates' in Visual Studio,
//     新建项目-->在线模板'New Project' --> 'Online Templates'
//
// 具体的F#专题,请看:For specific F# topics, see:
//     http://go.microsoft.com/fwlink/?LinkID=234174 (F#开发门户) (F# Development Portal)
//     http://go.microsoft.com/fwlink/?LinkID=124614 (代码库)(Code Gallery)
//     http://go.microsoft.com/fwlink/?LinkId=235173 (数学/统计编程)(Math/Stats Programming)
//     http://go.microsoft.com/fwlink/?LinkId=235176 (图表)(Charting)
// 内容Contents:
//    - 整型和基本函数Integers and basic functions
//    - 布尔值Booleans
//    - 字符串Strings
//    - 元组Tuples
//    - 列表和列表处理Lists and list processing
//    - 类Classes
//    - 泛型类Generic classes
//    - 实现接口Implementing interfaces
//    - 数组Arrays
//    - 数列Sequences
//    - 递归函数Recursive functions
//    - 记录类型Record types
//    - 联合类型Union types
//    - 选项类型Option types           
//    - 模式匹配Pattern matching       
//    - 计量单位Units of measure       
//    - 并行数组编程Parallel array programming
//    - 使用事件Using events
//    - 使用类型提供程序的Database访问Database access using type providers
//    - OData 访问使用提供程序类型OData access using type providers       最后这两个应该是关于数据库的,不会翻译,采用机翻

// ---------------------------------------------------------------
//        整型和基本函数 Integers and basic functions
// ---------------------------------------------------------------
module Integers =
    let sampleInteger = 176
    /// 对前面那个整数进行一些运算Do some arithmetic starting with the first integer
    let sampleInteger2 = (sampleInteger/4 + 5 - 7) * 4
    /// 从0到99的数的列表A list of the numbers from 0 to 99
    let sampleNumbers = [ 0 .. 99 ]
    /// 一个包含0到99的整数以及它们的平方的列表A list of all tuples containing all the numbers from 0 to 99 and their squares
    let sampleTableOfSquares = [ for i in 0 .. 99 -> (i, i*i) ]
    // 下一行代码打印了一个包含元组的列表,用%A进行通用输出The next line prints a list that includes tuples, using %A for generic printing
    printfn "The table of squares from 0 to 99 is:\n%A" sampleTableOfSquares

module BasicFunctions =
    // 用“let”关键字定义一个函数,该函数输入一个整数并返回一个整数Use 'let' to define a function that accepts an integer argument and returns an integer.
    let func1 x = x*x + 3            
    // 定义时函数参数可以加括号也可以不加Parenthesis are optional for function arguments
    let func1a (x) = x*x + 3            
    /// 使用这个函数,用“let”获取返回值Apply the function, naming the function return result using 'let'.
    /// 变量的类型时从函数的返回类型推断出来的The variable type is inferred from the function return type.
    let result1 = func1 4573
    printfn "整数4573的平方加3的结果是%d The result of squaring the integer 4573 and adding 3 is %d" result1
    // 如果需要,可以使用“(变量名:类型)”的格式显式地指定类型When needed, annotate the type of a parameter name using '(argument:type)'
    let func2 (x:int) = 2*x*x - x/5 + 3
    let result2 = func2 (7 + 4)
    printfn "对(7+4)应用第一个示例函数的结果是%d The result of applying the 1st sample function to (7 + 4) is %d" result2
    let func3 x =
        if x < 100.0 then
            2.0*x*x - x/5.0 + 3.0
        else
            2.0*x*x + x/5.0 - 37.0
    let result3 = func3 (6.5 + 4.5)
    printfn "对(6.5+4.5)应用第二个示例函数的结果是%f The result of applying the 2nd sample function to (6.5 + 4.5) is %f" result3

// ---------------------------------------------------------------
//        布尔值 Booleans
// ---------------------------------------------------------------
module SomeBooleanValues =
    let boolean1 = true
    let boolean2 = false
    let boolean3 = not boolean1 && (boolean2 || false)
    printfn "表达式 'not boolean1 && (boolean2 || false)' 的值是%A The expression 'not boolean1 && (boolean2 || false)' is %A" boolean3

// ---------------------------------------------------------------
//         字符串Strings
// ---------------------------------------------------------------
module StringManipulation =
    let string1 = "Hello"
    let string2  = "world"
    /// 用@符号创建一个不转义的字符串Use @ to create a verbatim string literal
    let string3 = @"c:\Program Files\"
    /// 使用三引号字面意义Using a triple-quote string literal
    let string4 = """He said "hello world" after you did"""
    let helloWorld = string1 + " " + string2 // 把两个字符串串在一起而且它们之间用空格分开concatenate the two strings with a space in between
    printfn "%s" helloWorld
    /// 一个由结果字符串的前7个字符组成的字符串A string formed by taking the first 7 characters of one of the result strings
    let substring = helloWorld.[0..6]
    printfn "%s" substring

// ---------------------------------------------------------------
//         元组(有序值集)Tuples (ordered sets of values)
// ---------------------------------------------------------------
module Tuples =
    /// 一个简单的整数元组A simple tuple of integers
    let tuple1 = (1, 2, 3)
    /// 一个可以交换一个元组中值的顺序的函数A function that swaps the order of two values in a tuple.
    /// 快速信息显示出该函数推断出具有泛型类型QuickInfo shows that the function is inferred to have a generic type.
    let swapElems (a, b) = (b, a)
    printfn "The result of swapping (1, 2) is %A" (swapElems (1,2))
    /// 一个由一个整数、一个字符串和一个双精度浮点数组成的元组A tuple consisting of an integer, a string, and a double-precision floating point number
    let tuple2 = (1, "fred", 3.1415)
    printfn "tuple1: %A    tuple2: %A" tuple1 tuple2
   

// ---------------------------------------------------------------
//        列表和列表处理 Lists and list processing
// ---------------------------------------------------------------
module Lists =
    let list1 = [ ]            ///一个空的列表 an empty list
    let list2 = [ 1; 2; 3 ]    /// 3个元素的列表 list of 3 elements
    let list3 = 42 :: list2    ///42加入到开头的新列表 a new list with '42' added to the beginning
    let numberList = [ 1 .. 1000 ]  /// 一个从1到1000整数的列表 list of integers from 1 to 1000
    ///一个包含了一年所有日期的列表 A list containing all the days of the year
    let daysList =
        [ for month in 1 .. 12 do
              for day in 1 .. System.DateTime.DaysInMonth(2012, month) do
                  yield System.DateTime(2012, month, day) ]
    /// 包含棋盘上黑白方格坐标的列表 A list containing the tuples which are the coordinates of the black squares on a chess board.
    let blackSquares =
        [ for i in 0 .. 7 do
              for j in 0 .. 7 do
                  if (i+j) % 2 = 1 then
                      yield (i, j) ]
    /// 将numberList里面的数平方,用管道运算符给List.map传递参数 Square the numbers in numberList, using the pipeline operator to pass an argument to List.map   
    let squares =
        numberList
        |> List.map (fun x -> x*x)
    ///计算被3整除的数的平方和 Computes the sum of the squares of the numbers divisible by 3.
    let sumOfSquares =
        numberList
        |> List.filter (fun x -> x % 3 = 0)
        |> List.sumBy (fun x -> x * x)

// ---------------------------------------------------------------
//         类Classes
// ---------------------------------------------------------------
module DefiningClasses =
    /// 这个类的构造函数有两个参数:dx和dy,都是float型(浮点型)的  注:Vector2D的意思是平面向量 The class's constructor takes two arguments: dx and dy, both of type 'float'.
    type Vector2D(dx : float, dy : float) =
        ///计算这个向量对象被构造的时候的长度 The length of the vector, computed when the object is constructed
        let length = sqrt (dx*dx + dy*dy)
        //“this”关键字表示对象自己 'this' specifies a name for the object's self identifier.
        //在实例方法中,它(指this)必须出现在成员名称之前 In instance methods, it must appear before the member name.
        member this.DX = dx 
        member this.DY = dy
        member this.Length = length
        member this.Scale(k) = Vector2D(k * this.DX, k * this.DY)
   
    /// Vector2D类的一个实例An instance of the Vector2D class
    let vector1 = Vector2D(3.0, 4.0)
    ///不修改原对象而得到一个新的缩放后的vector对象 Get a new scaled vector object, without modifying the original object
    let vector2 = vector1.Scale(10.0)
    printfn "Length of vector1: %f      Length of vector2: %f" vector1.Length vector2.Length

// ---------------------------------------------------------------
//         泛型类Generic classes
// ---------------------------------------------------------------
module DefiningGenericClasses =
    type StateTracker<'T>(initialElement: 'T) = // 'T是这个类的参数类型 'T is the type parameter for the class
        ///列表中的储存状态 Store the states in a list
        let mutable states = [ initialElement ]
        ///将一个新的元素假如到这个states列表 Add a new element to the list of states
        member this.UpdateState newState =
            states <- newState :: states  // 用“<-”运算符改变这个值 use the '<-' operator to mutate the value
        /// 得到这整个列表的历史states Get the entire list of historical states
        member this.History = states
        ///获取最新的状态 Get the latest state
        member this.Current = states.Head
    /// 这个泛型类的一个int类型的实例,请注意参数的类型是被推导出来的 An 'int' instance of the state tracker class. Note that the type parameter is inferred.
    let tracker = StateTracker 10
    // 添加状态Add a state
    tracker.UpdateState 17

// ---------------------------------------------------------------
//        实现接口 Implementing interfaces
// ---------------------------------------------------------------
///实现IDisposable接口 Type that implements IDisposable
type ReadFile() =
    let file = new System.IO.StreamReader("readme.txt")
    member this.ReadLine() = file.ReadLine()
    //这个类对IDisposable接口的实现 this class's implementation of IDisposable members
    interface System.IDisposable with   
        member this.Dispose() = file.Close()

// ---------------------------------------------------------------
//        数组 Arrays
// ---------------------------------------------------------------
module Arrays =
    ///空数组 The empty array
    let array1 = [| |]
    let array2 = [| "hello"; "world"; "and"; "hello"; "world"; "again" |]
    let array3 = [| 1 .. 1000 |]
    /// 只包含了单词“hello”和“world”的数组An array containing only the words "hello" and "world"
    let array4 = [| for word in array2 do
                        if word.Contains("l") then
                            yield word |]
    /// 按照索引包含了从0到2000中所有偶数的数组An array initialized by index and containing the even numbers from 0 to 2000
    let evenNumbers = Array.init 1001 (fun n -> n * 2)
    ///使用切片表示法提取的子数组 sub-array extracted using slicing notation
    let evenNumbersSlice = evenNumbers.[0..500]
    for word in array4 do
        printfn "word: %s" word
    // 用左箭头赋值运算符修改数组元素modify an array element using the left arrow assignment operator
    array2.[1] <- "WORLD!"
    /// 计算以h开头的 单词长度的总和Calculates the sum of the lengths of the words that start with 'h'
    let sumOfLengthsOfWords =
        array2
        |> Array.filter (fun x -> x.StartsWith "h")
        |> Array.sumBy (fun x -> x.Length)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值