F# curried function

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

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

6条回答
  •  有刺的猬
    2020-12-15 06:35

    It's a fairly simple process. Take a function, bind one of its arguments and return a new function. For example:

    let concatStrings left right = left + right
    let makeCommandPrompt= appendString "c:\> "
    

    Now by currying the simple concatStrings function, you can easily add a DOS style command prompt to the front of any string! Really useful!

    Okay, not really. A more useful case I find is when I want to have a make a function that returns me data in a stream like manner.

    let readDWORD array i = array[i] | array[i + 1] << 8 | array[i + 2] << 16 | 
        array[i + 3] << 24 //I've actually used this function in Python.
    

    The convenient part about it is that rather than creating an entire class for this sort of thing, calling the constructor, calling obj.readDWORD(), you just have a function that can't be mutated out from under you.

提交回复
热议问题