Loading ...
Sorry, an error occurred while loading the content.

Re: "ocaml_beginners"::[] How does Ocaml deduce function formal parameters?

Expand Messages
  • William D. Neumann
    ... This is because foo2 is equivalent to: let foo2 x = function y - y + 1 or similarly let foo2 x y = y + 1 The parameter x here (and the first x in your
    Message 1 of 5 , Sep 6, 2006
    • 0 Attachment
      On Wed, 6 Sep 2006, doug_arro wrote:

      > Hi,
      >
      > Can someone please enlighten me on how Ocaml decudes formal
      > parameters for a function? See the following example:
      >
      > # let foo = function x -> x + 1;;
      > val foo : int -> int = <fun>
      > # foo 1 ;;
      > -: int =2 ;;
      > # let foo2 x = function x -> x + 1;;
      > val foo2 : 'a -> int -> int = <fun>
      > # foo2 1 ;;
      > -: int -> int = <fun>
      > # let foo3 x = x + 1 ;;
      > val foo3 : int -> int = <fun>
      > # foo3 1 ;;
      > - : int = 2
      >
      > Why do foo and foo3 compute to the same value when being applied to 1
      > while foo2 computes to a function instead?

      This is because foo2 is equivalent to:
      let foo2' x = function y -> y + 1
      or similarly
      let foo2'' x y = y + 1

      The parameter x here (and the first x in your foo2) is unused in the inner
      computation. So what happens here is just what the code looks like, you
      pass something (anything) into foo2, and that something, whatever yt was,
      is thrown away, and the function (function y -> y+1) is returned as a
      result.

      William D. Neumann

      ---

      "There's just so many extra children, we could just feed the
      children to these tigers. We don't need them, we're not doing
      anything with them.

      Tigers are noble and sleek; children are loud and messy."

      -- Neko Case

      Life is unfair. Kill yourself or get over it.
      -- Black Box Recorder
    • Matt Gushee
      ... This is known as partial evaluation, and it can be quite useful. -- Matt Gushee
      Message 2 of 5 , Sep 6, 2006
      • 0 Attachment
        Martin Jambon wrote:

        > let foo2 x y = y + 1
        >
        > > # foo2 1 ;;
        > > -: int -> int = <fun>
        >
        > The second argument is missing, so you get a function which expects the
        > remaining argument.

        This is known as partial evaluation, and it can be quite useful.

        --
        Matt Gushee
        : Bantam - lightweight file manager : matt.gushee.net/software/bantam/ :
        : RASCL's A Simple Configuration Language : matt.gushee.net/rascl/ :
      Your message has been successfully submitted and would be delivered to recipients shortly.