How does currying work?

后端 未结 5 1601
误落风尘
误落风尘 2020-12-09 11:14

I\'m very new to Haskell and FP in general. I\'ve read many of the writings that describe what currying is, but I haven\'t found an explanation to how it actually works.

5条回答
  •  独厮守ぢ
    2020-12-09 11:45

    Something that may help is to think about how you could implement curry as a higher order function if Haskell didn't have built in support for it. Here is a Haskell implementation that works for a function on two arguments.

    curry :: (a -> b -> c) -> a -> (b -> c)
    curry f a = \b -> f a b
    

    Now you can pass curry a function on two arguments and the first argument and it will return a function on one argument (this is an example of a closure.)

    In ghci:

    Prelude> let curry f a = \b -> f a b
    Prelude> let g = curry (+) 5
    Prelude> g 10
    15
    Prelude> g 15
    20
    Prelude> 
    

    Fortunately we don't have to do this in Haskell (you do in Lisp if you want currying) because support is built into the language.

提交回复
热议问题