F# keyword 'Some'

前端 未结 3 594
闹比i
闹比i 2021-02-06 21:24

F# keyword \'Some\' - what does it mean?

相关标签:
3条回答
  • 2021-02-06 21:56

    Some is not a keyword. There is an option type however, which is a discriminated union containing two things:

    1. Some which holds a value of some type.
    2. None which represents lack of value.

    It's defined as:

    type 'a option =
        | None
        | Some of 'a
    

    It acts kind of like a nullable type, where you want to have an object which can hold a value of some type or have no value at all.

    let stringRepresentationOfSomeObject (x : 'a option) =
        match x with
        | None -> "NONE!"
        | Some(t) -> t.ToString()
    
    0 讨论(0)
  • 2021-02-06 21:57

    Some is used to specify an option type, or in other words, a type that may or may not exist.

    F# is different from most languages in that control flow is mostly done through pattern matching as opposed to traditional if/else logic.

    In traditional if/else logic, you may see something like this:

    if (isNull(x)) {
       do ...  
    } else {         //x exists
       do ...  
    }
    

    With pattern matching logic, matching we need a similar way to execute certain code if a value is null, or in F# syntax, None

    Thus we would have the same code as

    match x with 
      | None -> do ...
      | Some x -> do ... 
    
    0 讨论(0)
  • Can check out Discriminated Unions in F# for more info on DUs in general and the option type (Some, None) in particular. As a previous answer says, Some is just a union-case of the option<'a> type, which is a particularly common/useful example of an algebraic data type.

    0 讨论(0)
提交回复
热议问题