What is the difference between these two functions?

I have two functions:

let rev_flatten l = 
  List.fold_left (fun acc x -> List.fold_left (fun acc y -> y::acc) acc x) [] l

A type val rev_flatten : 'a list list -> 'a list = <fun>

and

let rev_flatten = 
  List.fold_left (fun acc x -> List.fold_left (fun acc y -> y::acc) acc x) []

A type val rev_flatten : '_a list list -> '_a list = <fun>


I think these are the same functions, at least the same functionality, but why do they have two different types? Why does the second have an element type _a? What is it?

+3
source share
3 answers

A type variable with an underscore as a prefix tells us that the variable is weakly polymorphic. A weakly polymorphic variable can be used with only one type, however, the compiler cannot deduce the exact type, therefore the type variable has an underscore.

When you provide an argument for the first time, the variable will no longer be polymorphic and will only be able to accept arguments of one type.

, , . , , , , List.fold_left .

Edit: ( eta) ( )?

, , . :

let count f =
  let inc = ref 0 in
  (fun x -> inc := !inc + 1; print_int !inc; f x);;

: ('a -> 'b) -> 'a -> 'b.

. :

let max' = count max;;
val max' : '_a -> '_a -> '_a = <fun>

:

let max'' x = count max x;;
val max'' : 'a -> 'a -> 'a = <fun>

, :

max' 1 2;;  (* prints 1 *)
max' 1 2;;  (* prints 2 *)
max' 1 2;;  (* prints 3 *)
max'' 1 2;; (* prints 1 *)
max'' 1 2;; (* prints 1 *)
max'' 1 2;; (* prints 1 *)

, , , , , , , .

, .

+4

'_a list list -> '_a list . , int list list, rev_flatten '_a list list -> 'a list, int list list -> int list

, : http://caml.inria.fr/resources/doc/faq/core.en.html

,

+2

ML. SO gasche: 'a ' _l?.

, ML , , , . , , undefined ( ). .

, () . - , , ( ). ML , .

() , .. . "" . (, .) - (fun x → expr). "".

, . - . - . - [] . - ref [] .

+2
source

All Articles