F# のツアー#Tour of F#

F# について学習する最善の方法は、F# コードを読み書きすることです。The best way to learn about F# is to read and write F# code. この記事は、F# 言語のいくつかの主な機能の手引きとしての役割を果たし、コンピューターで実行できるいくつかのコード スニペットを示します。This article will act as a tour through some of the key features of the F# language and give you some code snippets that you can execute on your machine. 開発環境を設定する方法については、Getting Started を参照してください。To learn about setting up a development environment, check out Getting Started.

2 つの主要な概念があるF#: 関数と型。There are two primary concepts in F#: functions and types. このツアーではこれら 2 つの概念には、言語の機能を強調します。This tour will emphasize features of the language which fall into these two concepts.

オンラインでのコードを実行します。Executing the code online

いない場合F#コンピューターにインストールされている、実行できるすべてのオンライン サンプルのFable REPLします。If you don't have F# installed on your machine, you can execute all of the samples online with the Fable REPL. Fable は言語にF#お使いのブラウザーで直接実行します。Fable is a dialect of F# that executes directly in your browser. REPL で次のサンプルを表示するチェック アウトサンプル > 学習 > のツアー F# Fable レプリケーションの左側のメニュー バーにTo view the samples that follow in the REPL, check out Samples > Learn > Tour of F# in the left-hand menu bar of the Fable REPL.

関数、およびモジュールFunctions and Modules

任意の F# プログラムの最も基本的な部分が関数編成モジュールします。The most fundamental pieces of any F# program are functions organized into modules. 関数出力を生成する入力に作業を実行し、で構成されるモジュール、F# でグループ化する主な方法であります。Functions perform work on inputs to produce outputs, and they are organized under Modules, which are the primary way you group things in F#. 使用して定義されている、 letバインド関数の名前し、その引数を定義します。They are defined using the let binding, which give the function a name and define its arguments.

module BasicFunctions = 

    /// You use 'let' to define a function. This one accepts an integer argument and returns an integer. 
    /// Parentheses are optional for function arguments, except for when you use an explicit type annotation.
    let sampleFunction1 x = x*x + 3

    /// Apply the function, naming the function return result using 'let'. 
    /// The variable type is inferred from the function return type.
    let result1 = sampleFunction1 4573

    // This line uses '%d' to print the result as an integer. This is type-safe.
    // If 'result1' were not of type 'int', then the line would fail to compile.
    printfn "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)'.  Parentheses are required.
    let sampleFunction2 (x:int) = 2*x*x - x/5 + 3

    let result2 = sampleFunction2 (7 + 4)
    printfn "The result of applying the 2nd sample function to (7 + 4) is %d" result2

    /// Conditionals use if/then/elif/else.
    ///
    /// Note that F# uses white space indentation-aware syntax, similar to languages like Python.
    let sampleFunction3 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 = sampleFunction3 (6.5 + 4.5)

    // This line uses '%f' to print the result as a float.  As with '%d' above, this is type-safe.
    printfn "The result of applying the 2nd sample function to (6.5 + 4.5) is %f" result3

let バインディングでは、値を他の言語での変数のような名前にバインドする方法も。let bindings are also how you bind a value to a name, similar to a variable in other languages. let バインドは不変既定では、値または関数の名前をバインドしたら、変更できないことを意味する、インプレースします。let bindings are immutable by default, which means that once a value or function is bound to a name, it cannot be changed in-place. これは、他の言語での変数とは対照的変更可能な時間で任意の時点でその値の意味を変更できます。This is in contrast to variables in other languages, which are mutable, meaning their values can be changed at any point in time. 変更可能なバインディングを必要とする場合は使用できますlet mutable ...構文。If you require a mutable binding, you can use let mutable ... syntax.

module Immutability =

    /// Binding a value to a name via 'let' makes it immutable.
    ///
    /// The second line of code fails to compile because 'number' is immutable and bound.
    /// Re-defining 'number' to be a different value is not allowed in F#.
    let number = 2
    // let number = 3

    /// A mutable binding.  This is required to be able to mutate the value of 'otherNumber'.
    let mutable otherNumber = 2

    printfn "'otherNumber' is %d" otherNumber

    // When mutating a value, use '<-' to assign a new value.
    //
    // Note that '=' is not the same as this.  '=' is used to test equality.
    otherNumber <- otherNumber + 1

    printfn "'otherNumber' changed to be %d" otherNumber

数値、ブール値、および文字列Numbers, Booleans, and Strings

.NET 言語として F# をサポートしています、同じ基になるプリミティブ型.NET 内に存在します。As a .NET language, F# supports the same underlying primitive types that exist in .NET.

さまざまな数値型は F# で表されます。 次に示します。Here is how various numeric types are represented in F#:

module IntegersAndNumbers = 

    /// This is a sample integer.
    let sampleInteger = 176

    /// This is a sample floating point number.
    let sampleDouble = 4.1

    /// This computed a new number by some arithmetic.  Numeric types are converted using
    /// functions 'int', 'double' and so on.
    let sampleInteger2 = (sampleInteger/4 + 5 - 7) * 4 + int sampleDouble

    /// This is a list of the numbers from 0 to 99.
    let sampleNumbers = [ 0 .. 99 ]

    /// This is 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) ]

    // 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

どのようなブール値を次に示し、基本的な条件付きロジックを実行するようになります。Here's what Boolean values and performing basic conditional logic looks like:

module Booleans =

    /// Booleans values are 'true' and 'false'.
    let boolean1 = true
    let boolean2 = false

    /// Operators on booleans are 'not', '&&' and '||'.
    let boolean3 = not boolean1 && (boolean2 || false)

    // This line uses '%b'to print a boolean value.  This is type-safe.
    printfn "The expression 'not boolean1 && (boolean2 || false)' is %b" boolean3

ここでは、どのような basic と文字列操作のようになります。And here's what basic string manipulation looks like:

module StringManipulation = 

    /// Strings use double quotes.
    let string1 = "Hello"
    let string2  = "world"

    /// Strings can also use @ to create a verbatim string literal.
    /// This will ignore escape characters such as '\', '\n', '\t', etc.
    let string3 = @"C:\Program Files\"

    /// String literals can also use triple-quotes.
    let string4 = """The computer said "hello world" when I told it to!"""

    /// String concatenation is normally done with the '+' operator.
    let helloWorld = string1 + " " + string2 

    // This line uses '%s' to print a string value.  This is type-safe.
    printfn "%s" helloWorld

    /// Substrings use the indexer notation.  This line extracts the first 7 characters as a substring.
    /// Note that like many languages, Strings are zero-indexed in F#.
    let substring = helloWorld.[0..6]
    printfn "%s" substring

タプルTuples

タプルは F# の大きな問題です。Tuples are a big deal in F#. これらは、値自体として扱うことができますが、名前のない、順序付けされた値のグループです。They are a grouping of unnamed, but ordered values, that can be treated as values themselves. それらの他の値からごとに集計値として考えます。Think of them as values which are aggregated from other values. 簡単に、関数から複数の値を返すまたはアドホック便宜上いくつかの値をグループ化など、数多くの用途があります。They have many uses, such as conveniently returning multiple values from a function, or grouping values for some ad-hoc convenience.

module Tuples =

    /// A simple tuple of integers.
    let tuple1 = (1, 2, 3)

    /// A function that swaps the order of two values in a tuple. 
    ///
    /// F# Type Inference will automatically generalize the function to have a generic type,
    /// meaning that it will work with any 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\ttuple2: %A" tuple1 tuple2

F# 4.1、作成することもstruct組。As of F# 4.1, you can also create struct tuples. これらも相互運用完全にも、C# 7/Visual Basic 15 タプルstruct組。These also interoperate fully with C#7/Visual Basic 15 tuples, which are also struct tuples:

/// Tuples are normally objects, but they can also be represented as structs.
///
/// These interoperate completely with structs in C# and Visual Basic.NET; however,
/// struct tuples are not implicitly convertible with object tuples (often called reference tuples).
///
/// The second line below will fail to compile because of this.  Uncomment it to see what happens.
let sampleStructTuple = struct (1, 2)
//let thisWillNotCompile: (int*int) = struct (1, 2)

// Although you can
let convertFromStructTuple (struct(a, b)) = (a, b)
let convertToStructTuple (a, b) = struct(a, b)

printfn "Struct Tuple: %A\nReference tuple made from the Struct Tuple: %A" sampleStructTuple (sampleStructTuple |> convertFromStructTuple)

ため、注意することが重要structタプルが値型、タプルを参照する暗黙的に変換することはできませんまたはその逆です。It's important to note that because struct tuples are value types, they cannot be implicitly converted to reference tuples, or vice versa. 参照と構造体のタプルの間で明示的に変換する必要があります。You must explicitly convert between a reference and struct tuple.

パイプラインと合成Pipelines and Composition

などの演算子をパイプ|>F# でのデータを処理するときに広く使用されます。Pipe operators such as |> are used extensively when processing data in F#. これらの演算子は、柔軟な方法で関数の「パイプライン」を確立するための関数です。These operators are functions that allow you to establish "pipelines" of functions in a flexible manner. 次の例では、方法を利用する機能の単純なパイプラインを構築するこれらの演算子の説明します。The following example walks through how you can take advantage of these operators to build a simple functional pipeline:

module PipelinesAndComposition =

    /// Squares a value.
    let square x = x * x

    /// Adds 1 to a value.
    let addOne x = x + 1

    /// Tests if an integer value is odd via modulo.
    let isOdd x = x % 2 <> 0

    /// A list of 5 numbers.  More on lists later.
    let numbers = [ 1; 2; 3; 4; 5 ]

    /// Given a list of integers, it filters out the even numbers,
    /// squares the resulting odds, and adds 1 to the squared odds.
    let squareOddValuesAndAddOne values = 
        let odds = List.filter isOdd values
        let squares = List.map square odds
        let result = List.map addOne squares
        result

    printfn "processing %A through 'squareOddValuesAndAddOne' produces: %A" numbers (squareOddValuesAndAddOne numbers)
    
    /// A shorter way to write 'squareOddValuesAndAddOne' is to nest each
    /// sub-result into the function calls themselves.
    ///
    /// This makes the function much shorter, but it's difficult to see the
    /// order in which the data is processed.
    let squareOddValuesAndAddOneNested values = 
        List.map addOne (List.map square (List.filter isOdd values))

    printfn "processing %A through 'squareOddValuesAndAddOneNested' produces: %A" numbers (squareOddValuesAndAddOneNested numbers)

    /// A preferred way to write 'squareOddValuesAndAddOne' is to use F# pipe operators.
    /// This allows you to avoid creating intermediate results, but is much more readable
    /// than nesting function calls like 'squareOddValuesAndAddOneNested'
    let squareOddValuesAndAddOnePipeline values =
        values
        |> List.filter isOdd
        |> List.map square
        |> List.map addOne

    printfn "processing %A through 'squareOddValuesAndAddOnePipeline' produces: %A" numbers (squareOddValuesAndAddOnePipeline numbers)

    /// You can shorten 'squareOddValuesAndAddOnePipeline' by moving the second `List.map` call
    /// into the first, using a Lambda Function.
    ///
    /// Note that pipelines are also being used inside the lambda function.  F# pipe operators
    /// can be used for single values as well.  This makes them very powerful for processing data.
    let squareOddValuesAndAddOneShorterPipeline values =
        values
        |> List.filter isOdd
        |> List.map(fun x -> x |> square |> addOne)

    printfn "processing %A through 'squareOddValuesAndAddOneShorterPipeline' produces: %A" numbers (squareOddValuesAndAddOneShorterPipeline numbers)

行われる前のサンプルの F# では、リスト処理関数をファーストクラスの関数を含む多くの機能の使用と部分適用します。The previous sample made use of many features of F#, including list processing functions, first-class functions, and partial application. これらの概念のそれぞれの深い理解がやや高度なことができますになる、する必要がありますがクリア関数を使用してパイプラインを構築するときにデータを処理する方法を簡単にします。Although a deep understanding of each of those concepts can become somewhat advanced, it should be clear how easily functions can be used to process data when building pipelines.

リスト、配列、およびシーケンスLists, Arrays, and Sequences

リスト、配列、およびシーケンスは、F# コア ライブラリの次の 3 つのプライマリ コレクション型です。Lists, Arrays, and Sequences are three primary collection types in the F# core library.

一覧表示は同じ型の要素の順序付けられた、変更できないコレクションです。Lists are ordered, immutable collections of elements of the same type. シングル リンク リスト、つまり、大規模な場合、列挙がランダム アクセスと連結するにはあまり適して本来は。They are singly-linked lists, which means they are meant for enumeration, but a poor choice for random access and concatenation if they're large. これは通常のリストを表すシングル リンク リストを使用しないでください、人気のある他の言語のリストとは対照的です。This in contrast to Lists in other popular languages, which typically do not use a singly-linked list to represent Lists.

module Lists =

    /// Lists are defined using [ ... ].  This is an empty list.
    let list1 = [ ]  

    /// This is a list with 3 elements.  ';' is used to separate elements on the same line.
    let list2 = [ 1; 2; 3 ]

    /// You can also separate elements by placing them on their own lines.
    let list3 = [
        1
        2
        3
    ]

    /// This is a list of integers from 1 to 1000
    let numberList = [ 1 .. 1000 ]  

    /// Lists can also be generated by computations. This is a list containing 
    /// all the days of the year.
    let daysList = 
        [ for month in 1 .. 12 do
              for day in 1 .. System.DateTime.DaysInMonth(2017, month) do 
                  yield System.DateTime(2017, month, day) ]

    // Print the first 5 elements of 'daysList' using 'List.take'.
    printfn "The first 5 days of 2017 are: %A" (daysList |> List.take 5)

    /// Computations can include conditionals.  This is 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) ]

    /// Lists can be transformed using 'List.map' and other functional programming combinators.
    /// This definition produces a new list by squaring the numbers in numberList, using the pipeline 
    /// operator to pass an argument to List.map.
    let squares = 
        numberList 
        |> List.map (fun x -> x*x) 

    /// There are many other list combinations. The following 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)

    printfn "The sum of the squares of numbers up to 1000 that are divisible by 3 is: %d" sumOfSquares

配列が固定サイズ変更可能な同じ型の要素のコレクション。Arrays are fixed-size, mutable collections of elements of the same type. 要素の高速なランダム アクセスをサポートし、F# リストのメモリ ブロックが連続するだけであるためよりも高速化されます。They support fast random access of elements, and are faster than F# lists because they are just contiguous blocks of memory.

module Arrays =

    /// This is The empty array.  Note that the syntax is similar to that of Lists, but uses `[| ... |]` instead.
    let array1 = [| |]

    /// Arrays are specified using the same range of constructs as lists.
    let array2 = [| "hello"; "world"; "and"; "hello"; "world"; "again" |]

    /// This is an array of numbers from 1 to 1000.
    let array3 = [| 1 .. 1000 |]

    /// This is an array containing only the words "hello" and "world".
    let array4 = 
        [| for word in array2 do
               if word.Contains("l") then 
                   yield word |]

    /// This is an array initialized by index and containing the even numbers from 0 to 2000.
    let evenNumbers = Array.init 1001 (fun n -> n * 2) 

    /// Sub-arrays are extracted using slicing notation.
    let evenNumbersSlice = evenNumbers.[0..500]

    /// You can loop over arrays and lists using 'for' loops.
    for word in array4 do 
        printfn "word: %s" word

    // You can modify the contents of an array element by using the left arrow assignment operator.
    //
    // To learn more about this operator, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/values/index#mutable-variables
    array2.[1] <- "WORLD!"

    /// You can transform arrays using 'Array.map' and other functional programming operations.
    /// The following 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)

    printfn "The sum of the lengths of the words in Array 2 is: %d" sumOfLengthsOfWords

シーケンスは論理的な一連の同じ型のすべての要素。Sequences are a logical series of elements, all of the same type. これらは、リストと配列を論理的な一連の要素に、"view"をすることのできるより一般的な型です。These are a more general type than Lists and Arrays, capable of being your "view" into any logical series of elements. これらも目立つことができるので遅延、つまり、必要な場合にのみ要素を計算することができます。They also stand out because they can be lazy, which means that elements can be computed only when they are needed.

module Sequences = 

    /// This is the empty sequence.
    let seq1 = Seq.empty

    /// This a sequence of values.
    let seq2 = seq { yield "hello"; yield "world"; yield "and"; yield "hello"; yield "world"; yield "again" }

    /// This is an on-demand sequence from 1 to 1000.
    let numbersSeq = seq { 1 .. 1000 }

    /// This is a sequence producing the words "hello" and "world"
    let seq3 = 
        seq { for word in seq2 do
                  if word.Contains("l") then 
                      yield word }

    /// This sequence producing the even numbers up to 2000.
    let evenNumbers = Seq.init 1001 (fun n -> n * 2) 

    let rnd = System.Random()

    /// This is an infinite sequence which is a random walk.
    /// This example uses yield! to return each element of a subsequence.
    let rec randomWalk x =
        seq { yield x
              yield! randomWalk (x + rnd.NextDouble() - 0.5) }

    /// This example shows the first 100 elements of the random walk.
    let first100ValuesOfRandomWalk = 
        randomWalk 5.0 
        |> Seq.truncate 100
        |> Seq.toList

    printfn "First 100 elements of a random walk: %A" first100ValuesOfRandomWalk

再帰関数Recursive Functions

コレクションまたは要素のシーケンス処理で通常実行再帰F# でします。Processing collections or sequences of elements is typically done with recursion in F#. F#サポートが for ループおよび命令型プログラミングでは、再帰をお勧めの正確性を保証するために簡単だからです。Although F# has support for loops and imperative programming, recursion is preferred because it is easier to guarantee correctness.

注意

次の例を使用してパターン マッチングの利用、match式。The following example makes use of the pattern matching via the match expression. この基本的な構成要素はこの記事の後半で説明します。This fundamental construct is covered later in this article.

module RecursiveFunctions = 
              
    /// This example shows a recursive function that computes the factorial of an 
    /// integer. It uses 'let rec' to define a recursive function.
    let rec factorial n = 
        if n = 0 then 1 else n * factorial (n-1)

    printfn "Factorial of 6 is: %d" (factorial 6)

    /// Computes the greatest common factor of two integers.
    ///
    /// Since all of the recursive calls are tail calls,
    /// the compiler will turn the function into a loop,
    /// which improves performance and reduces memory consumption.
    let rec greatestCommonFactor a b =
        if a = 0 then b
        elif a < b then greatestCommonFactor a (b - a)
        else greatestCommonFactor (a - b) b

    printfn "The Greatest Common Factor of 300 and 620 is %d" (greatestCommonFactor 300 620)

    /// This example computes the sum of a list of integers using recursion.
    let rec sumList xs =
        match xs with
        | []    -> 0
        | y::ys -> y + sumList ys

    /// This makes 'sumList' tail recursive, using a helper function with a result accumulator.
    let rec private sumListTailRecHelper accumulator xs =
        match xs with
        | []    -> accumulator
        | y::ys -> sumListTailRecHelper (accumulator+y) ys
    
    /// This invokes the tail recursive helper function, providing '0' as a seed accumulator.
    /// An approach like this is common in F#.
    let sumListTailRecursive xs = sumListTailRecHelper 0 xs

    let oneThroughTen = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

    printfn "The sum 1-10 is %d" (sumListTailRecursive oneThroughTen)

F#これは、ループ コンストラクトと同じ速度ように再帰呼び出しを最適化する方法、末尾呼び出し最適化を完全にサポートがあります。F# also has full support for Tail Call Optimization, which is a way to optimize recursive calls so that they are just as fast as a loop construct.

レコードと判別された共用体型Record and Discriminated Union Types

レコード、共用体の型は、F# コードで使用される 2 つの基本的なデータ型を一般に、F# プログラムでデータを表現する最善の方法は。Record and Union types are two fundamental data types used in F# code, and are generally the best way to represent data in an F# program. これにより、そのクラスのような他の言語は、構造的等値セマンティクスを備えることの主な違いの 1 つです。Although this makes them similar to classes in other languages, one of their primary differences is that they have structural equality semantics. つまり、「ネイティブ」の比較が等しいかどうかは簡単です - チェックのいずれかが、他と等しいかどうかだけです。This means that they are "natively" comparable and equality is straightforward - just check if one is equal to the other.

レコードは省略可能なメンバー (メソッドなど) と、名前付きの値の集計。Records are an aggregate of named values, with optional members (such as methods). C# または Java に詳しい場合は、し、これらように思われる Poco または Pojo - と同様に構造的等値と式だけです。If you're familiar with C# or Java, then these should feel similar to POCOs or POJOs - just with structural equality and less ceremony.

module RecordTypes = 

    /// This example shows how to define a new record type.  
    type ContactCard = 
        { Name     : string
          Phone    : string
          Verified : bool }
              
    /// This example shows how to instantiate a record type.
    let contact1 = 
        { Name = "Alf" 
          Phone = "(206) 555-0157" 
          Verified = false }

    /// You can also do this on the same line with ';' separators.
    let contactOnSameLine = { Name = "Alf"; Phone = "(206) 555-0157"; Verified = false }

    /// This example shows how to use "copy-and-update" on record values. It creates 
    /// a new record value that is a copy of contact1, but has different values for 
    /// the 'Phone' and 'Verified' fields.
    ///
    /// To learn more, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/copy-and-update-record-expressions
    let contact2 = 
        { contact1 with 
            Phone = "(206) 555-0112"
            Verified = true }

    /// This example shows how to write a function that processes a record value.
    /// It converts a 'ContactCard' object to a string.
    let showContactCard (c: ContactCard) = 
        c.Name + " Phone: " + c.Phone + (if not c.Verified then " (unverified)" else "")

    printfn "Alf's Contact Card: %s" (showContactCard contact1)

    /// This is an example of a Record with a member.
    type ContactCardAlternate =
        { Name     : string
          Phone    : string
          Address  : string
          Verified : bool }

        /// Members can implement object-oriented members.
        member this.PrintedContactCard =
            this.Name + " Phone: " + this.Phone + (if not this.Verified then " (unverified)" else "") + this.Address

    let contactAlternate = 
        { Name = "Alf" 
          Phone = "(206) 555-0157" 
          Verified = false 
          Address = "111 Alf Street" }
   
    // Members are accessed via the '.' operator on an instantiated type.
    printfn "Alf's alternate contact card is %s" contactAlternate.PrintedContactCard

F# 4.1、レコードとしても表現できますstruct秒。As of F# 4.1, you can also represent Records as structs. これは、[<Struct>]属性。This is done with the [<Struct>] attribute:

/// Records can also be represented as structs via the 'Struct' attribute.
/// This is helpful in situations where the performance of structs outweighs
/// the flexibility of reference types.
[<Struct>]
type ContactCardStruct = 
    { Name     : string
      Phone    : string
      Verified : bool }

判別共用体 (Du)は値の名前付きのフォームまたはケースの数である可能性があります。Discriminated Unions (DUs) are values which could be a number of named forms or cases. 型に格納されたデータには、いくつかの個別の値のいずれかを指定できます。Data stored in the type can be one of several distinct values.

module DiscriminatedUnions = 

    /// The following represents the suit of a playing card.
    type Suit = 
        | Hearts 
        | Clubs 
        | Diamonds 
        | Spades

    /// A Discriminated Union can also be used to represent the rank of a playing card.
    type Rank = 
        /// Represents the rank of cards 2 .. 10
        | Value of int
        | Ace
        | King
        | Queen
        | Jack

        /// Discriminated Unions can also implement object-oriented members.
        static member GetAllRanks() = 
            [ yield Ace
              for i in 2 .. 10 do yield Value i
              yield Jack
              yield Queen
              yield King ]
                                   
    /// This is a record type that combines a Suit and a Rank.
    /// It's common to use both Records and Discriminated Unions when representing data.
    type Card = { Suit: Suit; Rank: Rank }
              
    /// This computes a list representing all the cards in the deck.
    let fullDeck = 
        [ for suit in [ Hearts; Diamonds; Clubs; Spades] do
              for rank in Rank.GetAllRanks() do 
                  yield { Suit=suit; Rank=rank } ]

    /// This example converts a 'Card' object to a string.
    let showPlayingCard (c: Card) = 
        let rankString = 
            match c.Rank with 
            | Ace -> "Ace"
            | King -> "King"
            | Queen -> "Queen"
            | Jack -> "Jack"
            | Value n -> string n
        let suitString = 
            match c.Suit with 
            | Clubs -> "clubs"
            | Diamonds -> "diamonds"
            | Spades -> "spades"
            | Hearts -> "hearts"
        rankString  + " of " + suitString

    /// This example prints all the cards in a playing deck.
    let printAllCards() = 
        for card in fullDeck do 
            printfn "%s" (showPlayingCard card)

Du として使用することもできます。単一ケースの判別共用体、ドメイン モデリングのプリミティブ型を支援します。You can also use DUs as Single-Case Discriminated Unions, to help with domain modeling over primitive types. 多くの場合、文字列およびその他のプリミティブ型を表すもの、使用されはそのため、特定の意味が与えられます。Often times, strings and other primitive types are used to represent something, and are thus given a particular meaning. ただし、データのプリミティブの表現のみを使用しては、誤って正しくない値を割り当てることになることができます!However, using only the primitive representation of the data can result in mistakenly assigning an incorrect value! 個別の単一ケース共用体として情報の各型を表すと、このシナリオでは正確性を適用できます。Representing each type of information as a distinct single-case union can enforce correctness in this scenario.

// Single-case DUs are often used for domain modeling.  This can buy you extra type safety
// over primitive types such as strings and ints.
//
// Single-case DUs cannot be implicitly converted to or from the type they wrap.
// For example, a function which takes in an Address cannot accept a string as that input,
// or vice versa.
type Address = Address of string
type Name = Name of string
type SSN = SSN of int

// You can easily instantiate a single-case DU as follows.
let address = Address "111 Alf Way"
let name = Name "Alf"
let ssn = SSN 1234567890

/// When you need the value, you can unwrap the underlying value with a simple function.
let unwrapAddress (Address a) = a
let unwrapName (Name n) = n
let unwrapSSN (SSN s) = s

// Printing single-case DUs is simple with unwrapping functions.
printfn "Address: %s, Name: %s, and SSN: %d" (address |> unwrapAddress) (name |> unwrapName) (ssn |> unwrapSSN)

単一ケース判別された共用体、基になる値を取得する、上記のサンプルに示すように明示的に unwrap する必要があります。As the above sample demonstrates, to get the underlying value in a single-case Discriminated Union, you must explicitly unwrap it.

また、Du もサポート再帰的な定義では、ツリーと本質的に再帰型データを簡単に記述することができます。Additionally, DUs also support recursive definitions, allowing you to easily represent trees and inherently recursive data. たとえば、ここではどのでバイナリ検索ツリーを表すことができますexistsinsert関数。For example, here's how you can represent a Binary Search Tree with exists and insert functions.

/// Discriminated Unions also support recursive definitions.
///
/// This represents a Binary Search Tree, with one case being the Empty tree,
/// and the other being a Node with a value and two subtrees.
type BST<'T> =
    | Empty
    | Node of value:'T * left: BST<'T> * right: BST<'T>

/// Check if an item exists in the binary search tree.
/// Searches recursively using Pattern Matching.  Returns true if it exists; otherwise, false.
let rec exists item bst =
    match bst with
    | Empty -> false
    | Node (x, left, right) ->
        if item = x then true
        elif item < x then (exists item left) // Check the left subtree.
        else (exists item right) // Check the right subtree.

/// Inserts an item in the Binary Search Tree.
/// Finds the place to insert recursively using Pattern Matching, then inserts a new node.
/// If the item is already present, it does not insert anything.
let rec insert item bst =
    match bst with
    | Empty -> Node(item, Empty, Empty)
    | Node(x, left, right) as node ->
        if item = x then node // No need to insert, it already exists; return the node.
        elif item < x then Node(x, insert item left, right) // Call into left subtree.
        else Node(x, left, insert item right) // Call into right subtree.

Du するデータ型にツリーを再帰的な構造を表すため、この再帰構造で動作しているは簡単で、正確性が保証されます。Because DUs allow you to represent the recursive structure of the tree in the data type, operating on this recursive structure is straightforward and guarantees correctness. 次に示すパターン マッチングでもサポートされます。It is also supported in pattern matching, as shown below.

さらに、として Du を表すことができますstruct[<Struct>]属性。Additionally, you can represent DUs as structs with the [<Struct>] attribute:

/// Discriminated Unions can also be represented as structs via the 'Struct' attribute.
/// This is helpful in situations where the performance of structs outweighs
/// the flexibility of reference types.
///
/// However, there are two important things to know when doing this:
///     1. A struct DU cannot be recursively-defined.
///     2. A struct DU must have unique names for each of its cases.
[<Struct>]
type Shape =
    | Circle of radius: float
    | Square of side: float
    | Triangle of height: float * width: float

ただし、その際に留意する 2 つの重要事項があります。However, there are two key things to keep in mind when doing so:

  1. DU 構造体は、再帰的に定義することはできません。A struct DU cannot be recursively-defined.
  2. DU 構造体には、そのケースのそれぞれに一意の名前が必要です。A struct DU must have unique names for each of its cases.

上記に従わないは、コンパイル エラーになります。Failure to follow the above will result in a compilation error.

パターン マッチPattern Matching

パターン照合により、F# の型に対する操作のための正確性が F# 言語機能です。Pattern Matching is the F# language feature which enables correctness for operating on F# types. 上記のサンプルのことに気付いたのかなりmatch x with ...構文。In the above samples, you probably noticed quite a bit of match x with ... syntax. このコンス トラクターにより、コンパイラを強制すると、パターンの完全一致として呼ばれるものを通じて、データ型を使用する場合は、すべての可能なケースのアカウントに、データ型の「形状」を理解することができます。This construct allows the compiler, which can understand the "shape" of data types, to force you to account for all possible cases when using a data type through what is known as Exhaustive Pattern Matching. これは正しいかどうか、非常に強力な巧妙にどのようなコンパイル時にランタイムの問題は、通常「リフト」使用できます。This is incredibly powerful for correctness, and can be cleverly used to "lift" what would normally be a runtime concern into compile-time.

module PatternMatching =

    /// A record for a person's first and last name
    type Person = {
        First : string
        Last  : string
    }

    /// A Discriminated Union of 3 different kinds of employees
    type Employee =
        | Engineer of engineer: Person
        | Manager of manager: Person * reports: List<Employee>
        | Executive of executive: Person * reports: List<Employee> * assistant: Employee

    /// Count everyone underneath the employee in the management hierarchy,
    /// including the employee. The matches bind names to the properties 
    /// of the cases so that those names can be used inside the match branches.
    /// Note that the names used for binding do not need to be the same as the 
    /// names given in the DU definition above.
    let rec countReports(emp : Employee) =
        1 + match emp with
            | Engineer(person) ->
                0
            | Manager(person, reports) ->
                reports |> List.sumBy countReports
            | Executive(person, reports, assistant) ->
                (reports |> List.sumBy countReports) + countReports assistant


    /// Find all managers/executives named "Dave" who do not have any reports.
    /// This uses the 'function' shorthand to as a lambda expression.
    let rec findDaveWithOpenPosition(emps : List<Employee>) =
        emps
        |> List.filter(function
                       | Manager({First = "Dave"}, []) -> true // [] matches an empty list.
                       | Executive({First = "Dave"}, [], _) -> true
                       | _ -> false) // '_' is a wildcard pattern that matches anything.
                                     // This handles the "or else" case.

使用は、何かお気付き、_パターン。Something you may have noticed is the use of the _ pattern. これと呼ばれますが、ワイルドカード パターン、「気にしません何かが」と答えるのですが。This is known as the Wildcard Pattern, which is a way of saying "I don't care what something is". 、便利ですが誤ってバイパス徹底的なパターンに一致して不要になったコンパイル時の実施メリットを使用して注意が必要ない場合は_します。Although convenient, you can accidentally bypass Exhaustive Pattern Matching and no longer benefit from compile-time enforcements if you aren't careful in using _. 分解された型の特定の情報が必要ない場合に最適な使用パターン マッチ式内のすべての意味のあるケースを列挙するときと一致する、または最後の句のパターンします。It is best used when you don't care about certain pieces of a decomposed type when pattern matching, or the final clause when you have enumerated all meaningful cases in a pattern matching expression.

アクティブ パターンはパターン マッチングで使用する別の強力なコンストラクトです。Active Patterns are another powerful construct to use with pattern matching. それらの分解パターン一致の呼び出しサイトでカスタムのフォームに入力データをパーティション化できます。They allow you to partition input data into custom forms, decomposing them at the pattern match call site. これらもパラメーター化できる、ため関数として、パーティションを定義することができます。They can also be parameterized, thus allowing to define the partition as a function. アクティブ パターンをサポートするために、前の例を展開するようになります。Expanding the previous example to support Active Patterns looks something like this:

// Active Patterns are another powerful construct to use with pattern matching.
// They allow you to partition input data into custom forms, decomposing them at the pattern match call site. 
//
// To learn more, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/active-patterns
let (|Int|_|) = parseInt
let (|Double|_|) = parseDouble
let (|Date|_|) = parseDateTimeOffset
let (|TimeSpan|_|) = parseTimeSpan

/// Pattern Matching via 'function' keyword and Active Patterns often looks like this.
let printParseResult = function
    | Int x -> printfn "%d" x
    | Double x -> printfn "%f" x
    | Date d -> printfn "%s" (d.ToString())
    | TimeSpan t -> printfn "%s" (t.ToString())
    | _ -> printfn "Nothing was parse-able!"

// Call the printer with some different values to parse.
printParseResult "12"
printParseResult "12.045"
printParseResult "12/28/2016"
printParseResult "9:01PM"
printParseResult "banana!"

省略可能な型Optional Types

判別共用体の型の 1 つの特殊なケースは非常に役立つ、F# コア ライブラリの一部であるあるオプションの種類です。One special case of Discriminated Union types is the Option Type, which is so useful that it's a part of the F# core library.

オプションの種類は 2 つのケースのいずれかを表す型です: 値、またはまったくありません。The Option Type is a type which represents one of two cases: a value, or nothing at all. 値が場合がありますか、特定の操作からならない可能性がありますのシナリオで使用されます。It is used in any scenario where a value may or may not result from a particular operation. どちらの場合も、ランタイムの問題ではなく、コンパイル時の問題のためのアカウントに、必然です。This then forces you to account for both cases, making it a compile-time concern rather than a runtime concern. Api でよく使用されます、nullを代わりに、"nothing"を表す使用について心配する必要がなくなりますNullReferenceException多くの場合。These are often used in APIs where null is used to represent "nothing" instead, thus eliminating the need to worry about NullReferenceException in many circumstances.

/// Option values are any kind of value tagged with either 'Some' or 'None'.
/// They are used extensively in F# code to represent the cases where many other
/// languages would use null references.
///
/// To learn more, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/options
module OptionValues = 

    /// First, define a zip code defined via Single-case Discriminated Union.
    type ZipCode = ZipCode of string

    /// Next, define a type where the ZipCode is optional.
    type Customer = { ZipCode: ZipCode option }

    /// Next, define an interface type the represents an object to compute the shipping zone for the customer's zip code, 
    /// given implementations for the 'getState' and 'getShippingZone' abstract methods.
    type IShippingCalculator =
        abstract GetState : ZipCode -> string option
        abstract GetShippingZone : string -> int

    /// Next, calculate a shipping zone for a customer using a calculator instance.
    /// This uses combinators in the Option module to allow a functional pipeline for
    /// transforming data with Optionals.
    let CustomerShippingZone (calculator: IShippingCalculator, customer: Customer) =
        customer.ZipCode 
        |> Option.bind calculator.GetState 
        |> Option.map calculator.GetShippingZone

測定単位Units of Measure

F# の型システムの固有の機能を 1 つの単位を数値リテラルのコンテキストを提供する機能があります。One unique feature of F#'s type system is the ability to provide context for numeric literals through Units of Measure.

測定単位を使用すると、メートル単位などの単位に数値の種類の関連付けが関数を実行したり作業数値リテラルではなく、単位。Units of Measure allow you to associate a numeric type to a unit, such as Meters, and have functions perform work on units rather than numeric literals. これにより、コンパイラに渡された数値リテラルの型によって、特定のコンテキストで意味が、これにより、ランタイム エラー、その種の作業に関連付けられていることを確認できます。This enables the compiler to verify that the types of numeric literals passed in make sense under a certain context, thus eliminating runtime errors associated with that kind of work.

/// Units of measure are a way to annotate primitive numeric types in a type-safe way.
/// You can then perform type-safe arithmetic on these values.
///
/// To learn more, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/units-of-measure
module UnitsOfMeasure = 

    /// First, open a collection of common unit names
    open Microsoft.FSharp.Data.UnitSystems.SI.UnitNames

    /// Define a unitized constant
    let sampleValue1 = 1600.0<meter>          

    /// Next, define a new unit type
    [<Measure>]
    type mile =
        /// Conversion factor mile to meter.
        static member asMeter = 1609.34<meter/mile>

    /// Define a unitized constant
    let sampleValue2  = 500.0<mile>          

    /// Compute  metric-system constant
    let sampleValue3 = sampleValue2 * mile.asMeter   

    // Values using Units of Measure can be used just like the primitive numeric type for things like printing.
    printfn "After a %f race I would walk %f miles which would be %f meters" sampleValue1 sampleValue2 sampleValue3

F#コア ライブラリは、多くの SI 単位の種類および単位の変換を定義します。The F# Core library defines many SI unit types and unit conversions. 詳細についてにチェック アウト、 Microsoft.FSharp.Data.UnitSystems.SI Namespaceします。To learn more, check out the Microsoft.FSharp.Data.UnitSystems.SI Namespace.

クラスとインターフェイスClasses and Interfaces

F#.NET のクラスの完全なサポートがありますインターフェイス抽象クラス継承など。F# also has full support for .NET classes, Interfaces, Abstract Classes, Inheritance, and so on.

クラスは、.NET オブジェクトを表す型がプロパティ、メソッド、およびイベントであることができます、メンバーします。Classes are types that represent .NET objects, which can have properties, methods, and events as its Members.

/// Classes are a way of defining new object types in F#, and support standard Object-oriented constructs.
/// They can have a variety of members (methods, properties, events, etc.)
///
/// To learn more about Classes, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/classes
///
/// To learn more about Members, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/members
module DefiningClasses = 

    /// A simple two-dimensional Vector class.
    ///
    /// The class's constructor is on the first line,
    /// and takes two arguments: dx and dy, both of type 'double'.
    type Vector2D(dx : double, dy : double) =

        /// This internal field stores the length of the vector, computed when the 
        /// object is constructed
        let length = sqrt (dx*dx + dy*dy)

        // 'this' specifies a name for the object's self-identifier.
        // In instance methods, it must appear before the member name.
        member this.DX = dx

        member this.DY = dy

        member this.Length = length

        /// This member is a method.  The previous members were properties.
        member this.Scale(k) = Vector2D(k * this.DX, k * this.DY)
    
    /// This is how you instantiate the Vector2D class.
    let vector1 = Vector2D(3.0, 4.0)

    /// Get a new scaled vector object, without modifying the original object.
    let vector2 = vector1.Scale(10.0)

    printfn "Length of vector1: %f\nLength of vector2: %f" vector1.Length vector2.Length

ジェネリック クラスの定義も非常に簡単です。Defining generic classes is also very straightforward.

/// Generic classes allow types to be defined with respect to a set of type parameters.
/// In the following, 'T is the type parameter for the class.
///
/// To learn more, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/generics/
module DefiningGenericClasses = 

    type StateTracker<'T>(initialElement: 'T) = 

        /// This internal field store the states in a list.
        let mutable states = [ initialElement ]

        /// Add a new element to the list of states.
        member this.UpdateState newState = 
            states <- newState :: states  // use the '<-' operator to mutate the value.

        /// Get the entire list of historical states.
        member this.History = states

        /// Get the latest state.
        member this.Current = states.Head

    /// 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

インターフェイスを実装する、いずれかを使用できるinterface ... with構文またはオブジェクト式します。To implement an Interface, you can use either interface ... with syntax or an Object Expression.

/// Interfaces are object types with only 'abstract' members.
/// Object types and object expressions can implement interfaces.
///
/// To learn more, see: https://docs.microsoft.com/dotnet/fsharp/language-reference/interfaces
module ImplementingInterfaces =

    /// This is a type that implements IDisposable.
    type ReadFile() =

        let file = new System.IO.StreamReader("readme.txt")

        member this.ReadLine() = file.ReadLine()

        // This is the implementation of IDisposable members.
        interface System.IDisposable with
            member this.Dispose() = file.Close()


    /// This is an object that implements IDisposable via an Object Expression
    /// Unlike other languages such as C# or Java, a new type definition is not needed 
    /// to implement an interface.
    let interfaceImplementation =
        { new System.IDisposable with
            member this.Dispose() = printfn "disposed" }

使用する型Which Types to Use

クラス、レコード、判別共用体、およびタプルの存在が重要な質問につながります。 使用すべきでしょうか。The presence of Classes, Records, Discriminated Unions, and Tuples leads to an important question: which should you use? ほとんどライフで、すべてのように、答えは、状況によって異なります。Like most everything in life, the answer depends on your circumstances.

タプルは、関数から複数の値を返すおよびアドホック集計値の集計を使用して、自体の値として適しています。Tuples are great for returning multiple values from a function, and using an ad-hoc aggregate of values as a value itself.

レコードは、"からのステップ アップ"組、ラベルと省略可能なメンバーのサポートということです。Records are a "step up" from Tuples, having named labels and support for optional members. データ転送中のプログラムを儀礼的表現に適しています。They are great for a low-ceremony representation of data in-transit through your program. 構造の等値があるため比較で簡単に使用されます。Because they have structural equality, they are easy to use with comparison.

判別共用体は数多くの用途がコア特典がアカウントのすべての可能な「図形」ことができるデータに一致するパターンと組み合わせて利用するため可能になります。Discriminated Unions have many uses, but the core benefit is to be able to utilize them in conjunction with Pattern Matching to account for all possible "shapes" that a data can have.

クラスは、情報を表すしても機能するには、その情報を関連付ける必要がある場合などの理由の数が膨大に適しています。Classes are great for a huge number of reasons, such as when you need to represent information and also tie that information to functionality. ルールの一般的に、概念的には、一部のデータに関連する機能がある場合は、大きな利点にはクラスとオブジェクト指向プログラミングの原則を使用してます。As a rule of thumb, when you have functionality which is conceptually tied to some data, using Classes and the principles of Object-Oriented Programming is a big benefit. クラスも優先されるデータ型 c# と Visual Basic での相互運用するときにこれらの言語では、ほぼすべてのクラスを使用します。Classes are also the preferred data type when interoperating with C# and Visual Basic, as these languages use classes for nearly everything.

次の手順Next Steps

言語の主な機能のいくつかを確認したらには、最初の F# プログラムを作成できるようにする必要があります。Now that you've seen some of the primary features of the language, you should be ready to write your first F# programs! チェック アウトGetting Startedに開発環境を設定して、コードを記述する方法について説明します。Check out Getting Started to learn how to set up your development environment and write some code.

詳細は次の手順は任意できますが、お勧めしますで関数型プログラミングの概要F#コア関数型プログラミングの概念に慣れるにします。The next steps for learning more can be whatever you like, but we recommend Introduction to Functional Programming in F# to get comfortable with core Functional Programming concepts. これらは、F# で堅牢なアプリケーションの構築に不可欠になります。These will be essential in building robust programs in F#.

また、チェック アウト、 F# 言語リファレンスを F# の概念的なコンテンツの包括的なコレクションを参照してください。Also, check out the F# Language Reference to see a comprehensive collection of conceptual content on F#.