Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding `Monomorphism` Example of 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)

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)
like image 345
Kevin Meredith Avatar asked Jan 29 '15 02:01

Kevin Meredith


1 Answers

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>

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))
                      ^

This works as you would expect with the Shapeless approach.

like image 122
gzm0 Avatar answered Sep 18 '22 06:09

gzm0