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

问题描述

我正在学习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:

(添加了重点)

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

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

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

08-23 08:21