F# curried function

前端 未结 6 2379
独厮守ぢ
独厮守ぢ 2020-12-15 06:02

Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?

6条回答
  •  一生所求
    2020-12-15 06:37

    You know you can map a function over a list? For example, mapping a function to add one to each element of a list:

    > List.map ((+) 1) [1; 2; 3];;
    val it : int list = [2; 3; 4]
    

    This is actually already using currying because the (+) operator was used to create a function to add one to its argument but you can squeeze a little more out of this example by altering it to map the same function of a list of lists:

    > List.map (List.map ((+) 1)) [[1; 2]; [3]];;
    val it : int list = [[2; 3]; [4]]
    

    Without currying you could not partially apply these functions and would have to write something like this instead:

    > List.map((fun xs -> List.map((fun n -> n + 1), xs)), [[1; 2]; [3]]);;
    val it : int list = [[2; 3]; [4]]
    

提交回复
热议问题