Coding Practice for F#

后端 未结 4 1105
礼貌的吻别
礼貌的吻别 2021-02-04 10:44

I have been dabbling with F# in Visual Studio 2010. I am a developer with more code/architecture design experience in object-oriented languages such as C# and Java.

T

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 11:23

    In principle, your code is all right.

    There are just some points that can be simplified from a syntactical point of view.

    let ppl:(string * string) list = [
        ("1", "Jerry"); 
        ("2", "Max"); 
        ("3", "Andrew");
    ]
    

    The compiler is able to deduce most types by himself:

    let ppl = [ "1", "Jerry";
                "2", "Max";
                "3", "Andrew" ]
    

    And of course you can re-write your filters like this due to currying:

    let oddFilter (id:string, name:string) = (int id) % 2 = 1
    let allFilter (id:string, name:string) = true
    

    The biggest improvement would be separating the indices from the names and let the programm do the numbering. You don't have to work with strings instead of numbers and can use more idiomatic tuple-free functions:

    let ppl = [ "Jerry"; "Max"; "Andrew" ]
    
    let oddFilter id name = id % 2 = 1
    let allFilter id name = true
    
    let createPerson id name = ...
    

    The part

    ppl |> List.filter(filter)  |> List.map createPerson
    

    would be rewritten to

    [ for (index, name) in List.mapi (fun i x -> (i, x)) do
          if filter index name then
              yield createPerson (string index) name ]
    

提交回复
热议问题