类型推断:函数与类型 [英] Type inference: functions vs types

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

问题描述

我正在学习F#,但我不明白类型推断和泛型如何在这种语言中工作.例如,我可以声明一个通用的min函数,并将其与不同类型的参数一起使用:

I am learning F# and I don't understand how type inference and generics work in this language. For example, I can declare a generic min function and use it with parameters of different types:

let min a b = if a < b then a else b

let smallestInt = min 3 5
let smallestFloat = min 3.0 5.0

但是如果我尝试使用同一类型的东西,那是行不通的:

But if I try the same thing with a type, it doesn't work:

type Point2D(x, y) = 
    member this.X = x
    member this.Y = y

let float32Point = new Point2D(0.0f, 1.0f)
let intPoint = new Point2D(0, 1) // This expression was expected to have type 
                                 // float32 but here has type int

所以,我有几个问题:

  • 为什么我可以对不同类型重用通用函数定义,但不能对类型定义重用?
  • 函数是否像C#泛型那样在运行时专用于每种类型?还是像C ++模板那样在编译时?还是执行拳击以将每个参数都视为IComparable?

谢谢.

推荐答案

类需要显式类型参数.这有效:

Classes require explicit type parameters. This works:

type Point2D<'T>(x:'T, y:'T) = 
    member this.X = x
    member this.Y = y

let float32Point = Point2D(0.0f, 1.0f)
let intPoint = Point2D(0, 1)

要回答第二个问题,您对min的定义具有签名'a -> 'a -> 'a (requires comparison). comparison约束仅在编译时存在(运行时签名相同,减去约束).

To answer your second question, your definition of min has the signature 'a -> 'a -> 'a (requires comparison). The comparison constraint exists only at compile-time (the run-time signature is the same, minus the constraint).

<被具有约束的对GenericLessThanIntrinsic的调用替换.该约束仅传播给调用者.

< is replaced with a call to GenericLessThanIntrinsic, which has the constraint. The constraint is merely propagated to callers.

此外,根据规范的第14.6.7节:

Also, from section 14.6.7 of the spec:

泛化是在可能的情况下为定义推断泛型类型的过程,从而使构造可用于多种不同类型.默认情况下,通用化应用于所有函数,值和成员定义,除非本节稍后列出.泛化还适用于在对象表达式中实现泛型虚拟方法的成员定义.

Generalization is the process of inferring a generic type for a definition where possible, thereby making the construct reusable with multiple different types. Generalization is applied by default at all function, value, and member definitions, except where listed later in this section. Generalization also applies to member definitions that implement generic virtual methods in object expressions.

(添加了重点)

注意,列表中缺少类.我想它没有给出基本原理,但是它设计的.

Notice, classes are missing from the list. I suppose it doesn't give the rationale, but it is by design.

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

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