Ocaml% Identity Function

I wonder why we need a function like "% identity" that matches a = a. Will performance improve using it?

I present phantom input to my program, invoking ton identification functions for type conversion, curious if "% identity" can reduce the amount of overhead.

+5
source share
2 answers

The function %identityis part of the implementation, not part of the OCaml language. It tells the compiler (essentially) that there is nothing to do to change the function parameter to its return value. In other words, it tells the compiler to continue using the same value, but to change its idea of ​​the type. When used improperly, it basically eliminates all the excellent security guarantees of an OCaml system. In addition, of course, it does not guarantee work in any other language implementations (including future releases of the INRIA compiler).

The nesting capabilities of the OCaml compiler should already ensure that no code is generated for the authentication functions. Therefore, I would recommend that you continue to use them.

Update

... , :

let (<<) f g x = f (g x)
let id x = x

, :

# let sum l = List.fold_right (+) l 0;;
val sum : int list -> int = <fun>
# let product l = List.fold_right ( * ) l 1;;
val product : int list -> int = <fun>
# let composition l = List.fold_right (<<) l id;;
val composition : ('a -> 'a) list -> 'a -> 'a = <fun>

:

# sum [2; 3; 5; 7];;
- : int = 17
# product [2; 4; 17];;
- : int = 136
# let mx = composition [(+) 1; ( * ) 10];;
val mx : int -> int = <fun>
# mx 2;;
- : int = 21

, 0 , 1 id . id , , 0 1.

+10

%identity , (fun x -> x) , .

OCaml- %: bytecomp/translcore.ml AST node ( %identity Pidentity); node , . :

  • asmcomp/closure.ml 197 ss.: %identity, :

    begin match p with
      Pidentity -> make_const_int x
    | Pnegint -> make_const_int (-x)
    
  • asmcomp/cmmgen.ml 1047 ss.: %identity LHS :

    match p with
      (* Generic operations *)
        Pidentity ->
          transl arg
    

- .

+1

All Articles