ocaml%identity函数 [英] ocaml %identity function

查看:88
本文介绍了ocaml%identity函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我们需要像%identity"这样的函数,它与let a = a相同.使用它会提高性能吗?

I'm wondering why do we need function like "%identity", which is the same as let a = a. Is it going to improve performance by using it ?

我在程序中引入了幻像键入,多次调用身份函数来转换类型,很好奇%identity"是否可以减少一些开销.

I'm introducing phantom typing in my program, calling identity functions a ton times to convert types, curious if "%identity" can reduce a bit of overhead.

推荐答案

%identity函数是实现的一部分,而不是OCaml语言的一部分.它告诉编译器(本质上)无需执行任何操作即可将函数的参数更改为其返回值.换句话说,它告诉编译器继续使用相同的值,但更改其类型概念.如果使用不当,它基本上会使OCaml型系统的所有出色安全保证失效.而且,当然,不能保证它可以在该语言的任何其他实现中使用(包括INRIA编译器的将来版本).

The %identity function is part of the implementation, not part of the OCaml language. It tells the compiler (in essence) that there's nothing to do to change the function's parameter to its return value. In other words, it tells the compiler to keep using the same value but to change its idea of the type. If used incorrectly, it basically voids all the excellent safety guarantees of the OCaml type system. Also, of course, it's not guaranteed to work in any other implementations of the language (including future releases of the INRIA compiler).

OCaml编译器的内联功能应该已经保证不会为标识函数生成任何代码.因此,我建议您继续使用它们.

The inlining capability of the OCaml compiler should already guarantee that no code is generated for identity functions. So I would recommend that you just keep using them.

更新

要在注释中回答一个不相关的问题....假设您具有函数组成和标识函数:

To answer an unrelated question in the comments.... Assume you have function composition and the identity function:

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

然后是用于添加列表元素,将列表元素相乘以及组成列表中所有功能的函数:

Then here are functions to add the elements of a list, to multiply the elements of a list, and to compose all the functions in a list:

# 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一样.

The point is that 0 is the identity for addition, 1 for multiplication, and id for function composition. id is useful all the time, just as 0 and 1 are.

这篇关于ocaml%identity函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆