zoukankan      html  css  js  c++  java
  • F#小记——1. Hello F#

    简单的示例:

    首先我们来个传统函数式编程的hello world吧,一句话就可以了:

    printfn "hello world"

    这是典型的脚本语言的调用方式,当然,我们也可以试用传统的main函数的方式:

    [<EntryPoint>]

    let main (args : string[]) =

        printfn "hello world"

        // Program exit code

        0

    注意:入口函数是是通过EntryPoint这个Attribute标记的,而不是像C类语言那样固定为main。把它改成这样的方式也有同样的效果:

    [<EntryPoint>]

    let entrypoint (args : string[]) =

        printfn "hello world"

        // Program exit code

        0

    下面再来一个稍微复杂点的例子:

    (*

    Mega Hello World:

    Take two command line parameters and then print

    them along with the current time to the console.

    *)

     

    open System

     

    [<EntryPoint>]

    let main (args : string[]) =

        if args.Length <> 2 then

            failwith "Error: Expected arguments <greeting> and <thing>"

        let greeting, thing = args.[0], args.[1]

        let timeOfDay = DateTime.Now.ToString("hh:mm tt")

        printfn "%s, %s at %s" greeting thing timeOfDay

        // Program exit code

        0

    关于这个例子,这里并不多解释,相信有一定编程基础的人大都能看懂是什么意思。下面我就来简单的介绍一下了。

    变量:

    跳过前面的启动参数检测部分,首先定义了三个变量:greeting, thingtimeOfDay,并通过let关键字进行了变量的值的绑定。

        let greeting, thing = args.[0], args.[1]

        let timeOfDay = DateTime.Now.ToString("hh:mm tt")

    像大多数函数式语言一样,F#变量默认是immutable的,也就是说:变量一经赋值,就不能再改变它的值。这个特性对其开发并发或异步程序有很大帮助,关于这个F#变量的immutablemutable特性,后面再写专门文章来讨论的,这里就不多介绍了。

    缩进:

    F#可以通过缩进(空格)来表示作用域,如

        if args.Length <> 2 then

            failwith "Error: Expected arguments <greeting> and <thing>"

    如果写成这样的方式则无法通过编译:

        if args.Length <> 2 then

        failwith "Error: Expected arguments <greeting> and <thing>"

    初学者需要体会一下。

    .NET Interop

    作为.net 家族的一员,F#自然可以和.net framework无缝集成,使用方式也非常简单:

    open System

    // …

    let timeOfDay = DateTime.Now.ToString("hh:mm tt")

    使用方式上和C#非常类似,只是语法和关键字上稍微有些差异而已,后面再做详细介绍。

    注释:

    F#支持两种注释:行注释和块注释,在前面的例子中就有所体现:

    行注释是以“//”开头,一直到行尾,和C++/C#等语言一样。

    // Program exit code

    块注释则是通过“(*”和“*)”配合使用,其间的内容都是注释,可以换行。和C++/C#等语言的块注释/**/其实是一样的,只不过标示符不一样而已。

    (*

    Mega Hello World:

    Take two command line parameters and then print

    them along with the current time to the console.

    *)

    另外,和C#一样,F#中也支持通过“///”来表示XML注释,用以生成文档。

     

  • 相关阅读:
    [转]WebForm中使用MVC
    [转]外贸出口流程图
    [转]查看SQL Server被锁的表以及如何解锁
    [转]RDL Report in Visual Studio New page per Record
    [转]Sql Server Report Service 的部署问题
    [转]ASP.NET MVC4中@model使用多个类型实例的方法
    [转]告别写计划的烦恼!一页纸四步打造出一份牛逼的商业计划
    [转]LINQ: Using INNER JOIN, Group and SUM
    [转] 比特币『私钥』『公钥』『钱包地址』间的关系
    [转]SQL SERVER数据库删除LOG文件和清空日志的方案
  • 原文地址:https://www.cnblogs.com/TianFang/p/1771751.html
Copyright © 2011-2022 走看看