本文转自:http://msdn.microsoft.com/en-us/library/vstudio/dd233160(v=vs.100).aspx

 

Visual Studio 2010 includes a new programming language, F#. F# is a multiparadigm language that supports functional programming in addition to traditional object-oriented programming and .NET concepts. The following examples introduce some of its features and syntax. The examples show how to declare simple variables, to write and test functions, to create tuples and lists, and to define and use a class.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create a new console application

  1. On the File menu, point to New, and then click Project.

  2. If you cannot see Visual F# in the Templates Categories pane, click Other Languages, and then click Visual F#. The Templates pane in the center lists the F# templates.

  3. Look at the top of the Templates pane to make sure that .NET Framework 4 appears in the Target Framework box.

  4. Click F# Application in the list of templates.

  5. Type a name for your project in the Name field.

  6. Click OK.

    The new project appears in Solution Explorer.

To use the let keyword to declare and use identifiers

  • Copy and paste the following code into Program.fs. You are binding each identifier, anInt, aString, and anIntSquared, to a value.

    let anInt = 5
    let aString = "Hello"
    // Perform a simple calculation and bind anIntSquared to the result.
    let anIntSquared = anInt * anInt
    Note

    If you cannot see the code in Classic view, make sure that the Language Filter in the header below the topic title is set to include F#.

To see results in the F# Interactive window

  1. Select the let expressions in the previous procedure.

  2. Right-click the selected area and then click Send to Interactive. Alternatively, press ALT+ENTER.

  3. The F# Interactive window opens and the results of interpreting the let expressions are displayed, as shown in the following lines. The types are inferred from the specified values.

    val anInt : int = 5

    val aString : string = "Hello"

    val anIntSquared : int = 25

To see the results in a Command Prompt window

  1. Add the following lines to Program.fs.

    System.Console.WriteLine(anInt)
    System.Console.WriteLine(aString)
    System.Console.WriteLine(anIntSquared)
  2. Press CTRL+F5 to run the code. A Command Prompt window appears that contains the following values.

    5

    Hello

    25

    You can verify the inferred types by resting the mouse pointer on the identifier names anInt, aString, and anIntSquared in the previous WriteLine statements.

To define and run a function

  1. Use a let expression to define a squaring function, as shown in the following code. The function has one parameter, n, and returns the square of the argument sent to n.

    let square n = n * n
    // Call the function to calculate the square of anInt, which has the value 5.
    let result = square anInt
    // Display the result.
    System.Console.WriteLine(result)
  2. Press CTRL+F5 to run the code. The result displayed is 25.

  3. A recursive function requires a let rec expression. The following example defines a function that calculates the factorial of parameter n.

    let rec factorial n =
    if n = 0
    then 1
    else n * factorial (n - 1)
    System.Console.WriteLine(factorial anInt)
  4. Press CTRL+F5 to run the function. The result displayed is 120, the factorial of 5.

To create collections: lists and tuples

  1. One way to aggregate values is by using a tuple, as shown in the following code.

    let turnChoices = ("right", "left")
    System.Console.WriteLine(turnChoices)
    // Output: (right, left) let intAndSquare = (anInt, square anInt)
    System.Console.WriteLine(intAndSquare)
    // Output: (5,25)
  2. Another way to aggregate values is by using a list, as shown in the following code.

    // List of best friends.
    let bffs = [ "Susan"; "Kerry"; "Linda"; "Maria" ]

    Add a new best friend to the list by using the "cons" operator (::). Note that the operation does not change the value of bffs. The value of bffs is immutable and cannot be changed.

    // Bind newBffs to a new list that has "Katie" as its first element.
    let newBffs = "Katie" :: bffs

    Use printfn to display the lists. Function printfn shows the individual elements that are contained in structured values.

    printfn "%A" bffs
    // Output: ["Susan"; "Kerry"; "Linda"; "Maria"]
    printfn "%A" newBffs
    // Output: ["Katie"; "Susan"; "Kerry"; "Linda"; "Maria"]
  3. You can view the results either by pressing CTRL+F5 or by selecting a section of the code and then pressing ALT+ENTER.

To create and use a class

  1. The following code creates a Person class that has two properties, Name and Age. Name is a read-only property. Its value is immutable, as are most values in functional programming. You can create mutable values in F# if you need them, but you must explicitly define them as mutable. In the following class definition, the value of Age is stored in a mutable local variable, internalAge. The value of internalAge can be changed.

    // The declaration creates a constructor that takes two values, name and age.
    type Person(name:string, age:int) =
    // A Person object's age can be changed. The mutable keyword in the
    // declaration makes that possible.
    let mutable internalAge = age // Declare a second constructor that takes only one argument, a name.
    // This constructor calls the constructor that requires two arguments,
    // sending 0 as the value for age.
    new(name:string) = Person(name, 0) // A read-only property.
    member this.Name = name
    // A read/write property.
    member this.Age
    with get() = internalAge
    and set(value) = internalAge <- value // Instance methods.
    // Increment the person's age.
    member this.HasABirthday () = internalAge <- internalAge + 1 // Check current age against some threshold.
    member this.IsOfAge targetAge = internalAge >= targetAge // Display the person's name and age.
    override this.ToString () =
    "Name: " + name + "\n" + "Age: " + (string)internalAge
  2. To test the class, declare two Person objects, make some changes, and display the results, as shown in the following code.

    // The following let expressions are not part of the Person class. Make sure
    // they begin at the left margin.
    let person1 = Person("John", 43)
    let person2 = Person("Mary") // Send a new value for Mary's mutable property, Age.
    person2.Age <- 15
    // Add a year to John's age.
    person1.HasABirthday() // Display results.
    System.Console.WriteLine(person1.ToString())
    System.Console.WriteLine(person2.ToString())
    // Is Mary old enough to vote?
    System.Console.WriteLine(person2.IsOfAge(18))

    The following lines are displayed.

    Name:  John

    Age:   44

    Name:  Mary

    Age:   15

    False

To view other examples in the F# tutorial

  1. On the File menu, point to New, and then click Project.

  2. If you cannot see Visual F# in the Templates Categories pane, click Other Languages, and then click Visual F#. The Templates pane in the center lists the F# templates.

  3. Look at the top of the Templates pane to make sure that .NET Framework 4 appears in the Target Framework box.

  4. Click F# Tutorial in the list of templates.

  5. Click OK.

  6. The tutorial appears in Solution Explorer.

For more information about functional programming and additional examples, see Functions as First-Class Values (F#). For more information about tuples, lists, let expressions, function definitions, classes, members, and many other topics, see F# Language Reference.

[转]Walkthrough: Your First F# Program的更多相关文章

  1. awk -f program.file 功能使用

    一.awk -f program.file 功能使用 一直没有使用过awk的-f功能,感觉鸡肋,不是很实用,更多的是因为没有需求的原因 下面介绍下awk -f的使用方法 awk可以指定默认的文件路径, ...

  2. [转]Visual F# Samples and Walkthroughs

    本文转自:http://msdn.microsoft.com/en-US/library/vstudio/ee241126.aspx This topic provides links to samp ...

  3. 如果你也会C#,那不妨了解下F#(1):F# 数据类型

    本文链接:http://www.cnblogs.com/hjklin/p/fs-for-cs-dev-1.html 简单介绍 F#(与C#一样,念作"F Sharp")是一种基于. ...

  4. F#(1)

    如果你也会C#,那不妨了解下F#(1):F# 数据类型   简单介绍 F#(与C#一样,念作“F Sharp”)是一种基于.Net框架的强类型.静态类型的函数式编程语言.可以说C#是一门包含函数式编程 ...

  5. GLSL着色语言学习。橙皮书第一个例子GLSL+OpenTK+F#的实现。

    Opengl红皮书有选择的看了一些,最后的讲着色语言GLSL的部分看的甚为不理解,然后找到Opengl橙皮书,然后就容易理解多了. 在前面,我们或多或少接触到Opengl的处理过程,只说前面一些处理, ...

  6. [译]Python中的异步IO:一个完整的演练

    原文:Async IO in Python: A Complete Walkthrough 原文作者: Brad Solomon 原文发布时间:2019年1月16日 翻译:Tacey Wong 翻译时 ...

  7. Tesseract-OCR字符识别简介

    OCR(Optical Character Recognition):光学字符识别,是指对图片文件中的文字进行分析识别,获取的过程.Tesseract:开源的OCR识别引擎,初期Tesseract引擎 ...

  8. 开源发布:VS代码段快捷方式及可视化调试快速部署工具

    前言: 很久前,我发过两篇文章,分别介绍自定义代码版和可视化调试: 1:Visual Studio 小技巧:自定义代码片断 2:自定义可视化调试工具(Microsoft.VisualStudio.De ...

  9. 搭建selenium grid简单配置

    1.使用selenium提供的服务端独立jar包 :服务端.客户端都是运行于java7环境. 2.启动hub: hub配置文件如下: Java -jar selenium-server-standal ...

随机推荐

  1. IE将開始屏蔽旧版ActiveX控件

    微软IE团队上周宣布将在IE中屏蔽旧版本号的ActiveX控件以加强IE的安全性.首先会被禁用的旧版本号ActiveX控件包括: J2SE 1.4, 低于update 43 的版本号 J2SE 5.0 ...

  2. 实习生面试相关-b

    面试要准备什么 有一位小伙伴面试阿里被拒后,面试官给出了这样的评价:“……计算机基础,以及编程基础能力上都有所欠缺……”.但这种笼统的回答并非是我们希望的答案,所谓的基础到底指的是什么? 作为一名 i ...

  3. Java使用三种不同循环结构对1+2+3+...+100 求和

    ▷//第一种求法,使用while结构 /** * @author 9527 * @since 19/6/20 */ public class Gaosi { public static void ma ...

  4. 【大数据project师之路】Hadoop——MapReduce概述

    一.概述. MapReduce是一种可用于数据处理的编程模型.Hadoop能够执行由各种语言编写的MapReuce程序.MapReduce分为Map部分和Reduce部分. 二.MapReduce的机 ...

  5. 查看android-support-v4.jar引出的问题

    1.前面博文里也写过如何关联android-support-v4.jar的源码 今天新项目用上述方法的时候,竟然不成功..来回反复试了很长时间,最后发现 新建项目,会自动引用一个类库(自动新建的..) ...

  6. BZOJ1087=Codevs2451=洛谷P1896&P2326互不侵犯

    1087: [SCOI2005]互不侵犯King Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 2885  Solved: 1693[Submit][ ...

  7. java8--多线程(java疯狂讲义3复习笔记)

    多线程这块,平时用的框架里都封装好了,只有写批处理和工具包时用过几次.现在水平仅仅限于会用的程度,需要全面深入学习多线程. 主要内容:创建线程,启动线程,控制线程,多线程的同步,线程池,使用线程安全的 ...

  8. [NOIP2012] day2 T3疫情控制

    题目描述 H 国有 n 个城市,这 n 个城市用 n-1 条双向道路相互连通构成一棵树,1 号城市是首都,也是树中的根节点. H 国的首都爆发了一种危害性极高的传染病.当局为了控制疫情,不让疫情扩散到 ...

  9. 嵌入式Linux内核+根文件系统构建工具-Buildroot 快速入手指导【转】

    本文转载自:https://my.oschina.net/freeblues/blog/596448 嵌入式Linux内核+根文件系统构建工具-Buildroot 快速入手指导 buildroot 是 ...

  10. 并不对劲的AC自动机

    这像是能解决所有问题的样子(并不).AC自动机之所以叫AC自动机是因为它能解决所有AC自动机的题. 其实只能解决的是很多模式串匹配一个母串的问题. 把kmp中的next数组得到下一次跳转的位置看成特殊 ...