ML function currying

情到浓时终转凉″ 提交于 2019-12-12 13:06:36

问题


Could someone please explain the concept of currying to me. I am primarily learning it because we are learning ML in my 'modern programming language' class for a functional language introduction.

In particular you can use this example:

    -fun g a = fn b => a+b;
      val g = fn: int -> int -> int
    -g 2 3;
      val it = 5 : int

I'm confused how these parameters are passed or how to even think about it in the first place.

Thank you for any help.


回答1:


In this case, you make the currying explicit, so it should be easier to understand.

If we read the function definition, it says (paraphrased): "Create a function g, which when given an a returns fn b => a+b."

That is, if we call g 2, we get back the function fn b => 2+b. As such, when we call g 2 3, we actually call (g 2) 3; that is we first get the function stated above back, and then use this function on the value 3, yielding 5.

Currying is simply the concept of making a function in several "stages", each taking an input and producing a new function. SML has syntactic sugar for this, making g equivalent to the following:

fun g a b = a + b;


来源:https://stackoverflow.com/questions/12906348/ml-function-currying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!