UnSat
UnSat

Reputation: 1407

Can we define a function with 0 argument in ocaml?

In other languages, we can have a function which takes no arguments. Can we have 0 argument function in ocaml?

Upvotes: 6

Views: 4131

Answers (3)

Michaël Le Barbier
Michaël Le Barbier

Reputation: 6468

In OCaml functions always have an arguments. Therefore, we might wonder how to translate the following say_hello C function in OCaml:

void
say_hello()
{
    printf("Hello, world!\n");
}

There is a special type unit in OCaml which has only one value, written as (). While it might look odd and useless, it adds regularity to the language: a function not needing a specific argument can just take an argument of type unit, a function not returning a useful value usually returns a value of type unit. Here is how to translate the above say_hello function to OCaml:

# let say_hello () = print_endline "Hello, world!";;
val say_hello : unit -> unit = <fun>

Incidentally, template based meta-programming would be much easier in C++ if there were no type void but a similar unit type instead. It is quite common to treat separately functions having no arguments in template specialisations.


Object methods, while being similar to functions, do not require an argument.

# class example =
object
  method a =
    print_endline "This demonstrates a call to method a of class example"
end;;
        class example : object method a : unit end
# let x = new example;;
val x : example = <obj>
# x # a ;;
This demonstrates a call to method a of class example
- : unit = ()

Upvotes: 4

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

Functions in OCaml have exactly one argument (ignoring complications due to optional arguments). So, you can't have a function with no arguments.

As @alfa64 says, you could consider a simple value as a function with no arguments. But it will always have the same value (which, in fact, makes it similar to a pure function).

If you want to write a function that doesn't actually require any arguments (one that has side effects, presumably), it is traditional to use () as its argument:

# let p () = Printf.printf "hello, world\n";;
val p : unit -> unit = <fun>
# p ();;
hello, world
- : unit = ()
# 

Upvotes: 8

AlfredoVR
AlfredoVR

Reputation: 4287

Instead of

let foo n = 55

You just

let foo = 55

And then call foo wherever.

Upvotes: 0

Related Questions