类型构造函数作为返回类型 [英] Type Constructor as Return Type

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

问题描述

在Scala中,我可以定义代数数据类型:

In Scala, I can define an Algebraic Data Type:

scala> sealed trait Maybe[A]
defined trait Maybe

scala> case class Just[A](x: A) extends Maybe[A]
defined class Just

scala> case object NothingHere extends Maybe[Nothing]
defined object NothingHere

可以返回类型为Maybe[A]的函数f.

It's possible to return a function, f, with a return type of Maybe[A].

scala> def f[A](x: A): Maybe[A] = Just(x)
f: [A](x: A)Maybe[A]

但是,也可以指定返回Just[A].

However, it's also possible to specify that a Just[A] is returned.

scala> def f[A](x: A): Just[A] = Just(x)
f: [A](x: A)Just[A]

现在,我将在Haskell中进行类似的练习:

Now I'll do the similar exercise in Haskell:

Prelude> data Option a = None | Some a deriving Show
Prelude> let f x = Some x :: Option Int
Prelude> f 10
Some 10

但是,我无法设置类型构造函数的返回类型.

Prelude> let f x = Some x :: Some Int

<interactive>:10:21:
    Not in scope: type constructor or class `Some'
    A data constructor of that name is in scope; did you mean DataKinds?
Prelude> let f x = None :: None

Scala的Just是一个类,即合法的返回类型,这是简单的区别吗?而在Haskell中,类型构造函数不能是返回类型吗?

Is the simple difference that Scala's Just is a class, i.e. a legitimate return type? Whereas, in Haskell, a type constructor cannot be a return type?

推荐答案

区别在于Scala选择了实现ADT的方式. Scala使用案例类以OOP样式扩展特征,因此每种案例都是其自己的类型,而Haskell只是具有针对同一类型的多个构造函数.由于它们不是单独的类型,而是本质上只是单独的函数,因此您无法在类型级别上对其进行区分.有一些扩展使您能够区分类型级别,但它与Scala的功能不同.试图将Haskell的字体系统适合Scala的字体系统并不是最好的主意.

The difference is how Scala chose to implement ADTs. Scala uses case classes that extend a trait in an OOP style, so each case is its own type, whereas Haskell just has multiple constructors for the same type. Since they aren't separate types but essentially just separate functions, you can't distinguish them at the type level. There are extensions that give you some ability to make that type level distinction, but it won't be the same thing as what Scala has. And trying to fit Haskell's type system into Scala's type system is probably not the best of ideas.

简而言之,Scala使用继承形式来近似ADT,而Haskell只是具有ADT.

In short, Scala approximates ADTs using a form of inheritance, whereas Haskell just has ADTs.

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

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