Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `fun x -> x` the only function that has type 'a -> 'a in OCaml?

The title is the question, simple.

The identity function fun x -> x has the type 'a -> 'a.

Are there any other functions with the same type 'a -> 'a?

I can't think of another.

like image 365
Jackson Tale Avatar asked Jan 17 '13 14:01

Jackson Tale


People also ask

What does fun mean in OCaml?

Similarly, OCaml functions do not have to have names; they may be anonymous. For example, here is an anonymous function that increments its input: fun x -> x + 1 . Here, fun is a keyword indicating an anonymous function, x is the argument, and -> separates the argument from the body.

What does arrow mean in OCaml?

The operator is usually called type arrow where T1 -> T2 represents functions from type T1 to type T2 . For instance, the type of + is int -> (int -> int) because it takes two integers and returns another one.

How do you define a function in a function OCaml?

Using Operator as Function Operators, such as + * etc, can be considered as functions of 2 parameters. They can be used as a function in ocaml. A function call has the form f arg1 arg2 with function named f , while operator such as + is used in the form arg1 + arg2 .

Is OCaml purely functional?

ML-derived languages like OCaml are "mostly pure". They allow side-effects through things like references and arrays, but by and large most of the code you'll write will be pure functional because they encourage this thinking.


1 Answers

No.

fun x -> print_endline "foo"; x;;

(failwith "bang" : 'a -> 'a);;

(fun x -> failwith "bang" : 'a -> 'a);;

(fun x -> List.hd [] : 'a -> 'a);;

let rec f (x : 'a) : 'a = f x;;

let counter = ref 0;;
(fun x -> incr counter; x);;

The identity function is the only inhabitant of 'a -> 'a in total programming language with no side-effects whatsoever, including nontermination. Neither OCaml nor Haskell qualify, but some languages used as proof assistants (where this totality is important) do, in particular Coq (which has the impredicative polymorphism used to formulate this type).

like image 104
gasche Avatar answered Dec 16 '22 00:12

gasche