Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call map method in function with cats library

I'm reading Advanced Scala With Cats. I stuck on this example at functor description (page 59):

object FunctorsDemo extends App {

  import cats.instances.function._
  import cats.syntax.functor._

  val func1 = (x: Int) => x.toDouble
  val func2 = (y: Double) => y * 2

  val func3 = func1.map(func2) // wrong line for me

}

In book everything is okay, but I have this exception:

Error:(10, 21) value map is not a member of Int => Double
  val func3 = func1.map(func2)

Can't understand what I'm doing wrong.

like image 923
faoxis Avatar asked Sep 16 '18 14:09

faoxis


2 Answers

Here is one configuration with the exact version numbers for which it works:

build.sbt:

libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"
scalaVersion := "2.12.5"
scalacOptions += "-Ypartial-unification"

Code (FunctionIntDoubleFunctor.scala in same directory as build.sbt):

object FunctionIntDoubleFunctor {

  def main(args: Array[String]) {
    import cats.syntax.functor._

    import cats.instances.function._

    val func1 = (x: Int) => x.toDouble
    val func2 = (y: Double) => y * 2


    val func3 = func1.map(func2)
    println(func3(21)) // prints 42.0
  }

}

Ammonite with @ interp.configureCompiler(_.settings.YpartialUnification.value = true) fails miserably on exactly the same code, and I don't know why, so maybe it has something to do with the tools you are using.

like image 72
Andrey Tyukin Avatar answered Sep 17 '22 02:09

Andrey Tyukin


You have encountered a bug in Scala's type inference, the partial unification bug.

Add this to your build.sbt:

scalacOptions += "-Ypartial-unification"

There's a good writeup about it here if you're interested: https://gist.github.com/djspiewak/7a81a395c461fd3a09a6941d4cd040f2

like image 38
Tom Avatar answered Sep 17 '22 02:09

Tom