理解“Monomorphism"无形的例子 [英] Understanding `Monomorphism` Example of Shapeless

查看:45
本文介绍了理解“Monomorphism"无形的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Shapeless 功能概述显示了以下示例:>

The Shapeless Features Overview shows the following example:

import poly._

// choose is a function from Sets to Options with no type specific cases
object choose extends (Set ~> Option) {
  def apply[T](s : Set[T]) = s.headOption
}

scala> choose(Set(1, 2, 3))
res0: Option[Int] = Some(1)

scala> choose(Set('a', 'b', 'c'))
res1: Option[Char] = Some(a)

但是,由于缺乏使用 Shapeless 的经验,我不明白这与以下内容之间的区别:

However, I don't, in m lack of experience with Shapeless, understand the difference between that and the following:

scala> def f[T](set: Set[T]): Option[T] = set.headOption
f: [T](set: Set[T])Option[T]

scala> f( Set(1,2,3) )
res0: Option[Int] = Some(1)

scala> f( Set('a', 'b', 'c') )
res1: Option[Char] = Some(a)

推荐答案

这里的重要区别在于,choose 是一个可以作为值传递的函数.你不能从 f 中创建一个(合理的)值,因为 Scala 不支持多态函数值:

The important difference here is, that choose is a function that can be passed around as value. You cannot make a (reasonable) value out of f, since Scala does not support polymorphic function values:

scala> val fun = f _
fun: Set[Nothing] => Option[Nothing] = <function1>

如您所见,Scala 将元素类型固定为 Nothing,从而使函数对非空集无用:

As you see, Scala fixes the element type to Nothing rendering the function useless for non-empty sets:

scala> fun(Set(1))
<console>:10: error: type mismatch;
 found   : Int(1)
 required: Nothing
              fun(Set(1))
                      ^

这与使用 Shapeless 方法时所期望的一样.

This works as you would expect with the Shapeless approach.

这篇关于理解“Monomorphism"无形的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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