melling / ComputerLanguages

My personal notes on various computer languages
Creative Commons Zero v1.0 Universal
221 stars 18 forks source link

ocaml.org: Function can have multiple arguments #1

Open eprochasson opened 8 years ago

eprochasson commented 8 years ago

I'm not sure I follow what you say when you write A function always has exactly one parameter, and returns one result.. Functions can have multiple arguments:

(* In the REPL *)
utop# min;;
- : 'a -> 'a -> 'a = <fun>

min takes 2 arguments of type 'a and returns one value of type 'a. They can then be partially applied:

utop # let my_min = min 2;;
val my_min : int -> int = <fun>

returns a new function that takes one argument and return one value (the smallest one between the argument and 2), that one can use like:

my_min 1
-: int = 1

my_min 3
-: int = 2

More directly

utop # let my_fn s1 s2 = printf "Argument 1: %s, Argument 2: %s\n" s1 s2;;
val my_fn : string -> string -> unit = <fun>

utop # my_fn "hello" "world";;
Argument 1: hello, Argument 2: world
- : unit = ()
melling commented 8 years ago

I thought OCaml used currying, and while you may see multiple parameters, it's actually handled one parameter at a time?

eprochasson commented 8 years ago

I don't know how the implementation is actually done (I doubt it curries everything every time), and although you might be right, function can still be declared and take multiple parameters. You can easily try it for yourself. The fact that under the hood it uses single argument function or not does not have much influence on the way you declare and use functions.