Scala and Python's pass - scala

I was wondering, is there an equivalent of python's pass expression? The idea is to write method signatures without implementations and compiling them just to type-check those signatures for some library prototyping. I was able to kind of simulate such behavior using this:
def pass[A]:A = {throw new Exception("pass"); (new Object()).asInstanceOf[A]}
now when i write:
def foo():Int = bar()
def bar() = pass[Int]
it works(it typechecks but runtime explodes, which is fine), but my implementation doesn't feel right (for example the usage of java.lang.Object()). Is there better way to simulate such behavior?

In Scala 2.10, there is the ??? method in Predef.
scala> ???
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:252)
...
In 2.9, you can define your own one like this:
def ???[A]:A = throw new Exception("not implemented")
If you use this version without an explicit type paramter, A will be inferred to be Nothing.

Related

How to obtain a tree for a higher-kinded type parameter in a scala macro

I'm trying to write a macro to simplify some monad-related code (I'm using cats 1.6.0 for the Monads). For now I just want to be able to write lift[F](a) where F is a unary type constructor, and have that expand to a.pure[F]. Seems simple enough, but I can't get it working.
For now I have this code to help with type inference:
object Macros {
class LiftPartiallyApplied[F[_]] {
def apply[A](a: A): F[A] = macro MacroImpl.liftImpl[F, A]
}
def lift[F[_]] = new LiftPartiallyApplied[F]
}
And for the actual implementation of the macro:
object MacroImpl {
def liftImpl[F[_], A](c: blackbox.Context)(a: c.Tree)(implicit tt: c.WeakTypeTag[F[_]]): c.Tree = {
import c.universe._
q"$a.pure[${tt.tpe.typeConstructor}]"
}
}
Now I can call the macro like this lift[List](42) and it'll expand to 42.pure[List], great. But when I call it with a more complicated type, like lift[({type F[A] = Either[String, A]})#F](42), It'll expand to 42.pure[Either], which is obviously broken, because Either is a binary type constructor and not a unary one. The problem is I just don't know what to put there instead of ${tt.tpe.typeConstructor}…
// edit: since people apparently have trouble reproducing the problem, I've made a complete repository:
https://github.com/mberndt123/macro-experiment
I will now try to figure out what the difference between Dmytro's and my own project is.
Don't put Main and Macros to the same compilation unit.
But when I call it with a more complicated type, like lift[({type F[A] = Either[String, A]})#F](42), It'll expand to 42.pure[Either]
Can't reproduce.
For me lift[List](42) produces (with scalacOptions += "-Ymacro-debug-lite")
Warning:scalac: 42.pure[List]
TypeApply(Select(Literal(Constant(42)), TermName("pure")), List(TypeTree()))
at compile time and List(42) at runtime.
lift[({ type F[A] = Either[String, A] })#F](42) produces
Warning:scalac: 42.pure[[A]scala.util.Either[String,A]]
TypeApply(Select(Literal(Constant(42)), TermName("pure")), List(TypeTree()))
at compile time and Right(42) at runtime.
This is my project https://gist.github.com/DmytroMitin/334c230a4f2f1fd3fe9e7e5a3bb10df5
Why do you need macros? Why can't you write
import cats.Applicative
import cats.syntax.applicative._
class LiftPartiallyApplied[F[_]: Applicative] {
def apply[A](a: A): F[A] = a.pure[F]
}
def lift[F[_]: Applicative] = new LiftPartiallyApplied[F]
?
Allright, I found out what the problem was.
Macros need to be compiled separately from their use sites. I thought that this meant that Macros needs to be compiled separately from MacroImpl, so I put those in separate sbt subprojects, and I called the macro in the project where Macros is defined. But what it in fact means is that calls of the macro need to be compiled separately from its definition. So I put MacroImpl and Macros in one subproject and called the macro in another and it worked perfectly.
Thanks to Dmytro for taking the time to demonstrate how to do it right!
// edit: looks like Dmytro beat me to it with his comment :-)

Understanding Scala Implicits

While reading Functional Programming in Scala by Chiusano and Bjarnason, I encountered the following code in chapter 9, Parser Combinators:
trait Parsers[ParseError, Parser[+_]] { self =>
...
def or[A](s1: Parser[A], s2: Parser[A]): Parser[A]
implicit def string(s: String): Parser[String]
implicit def operators[A](p: Parser[A]) = ParserOps[A](p)
implicit def asStringParser[A](a: A)(implicit f: A => Parser[String]):
ParserOps[String] = ParserOps(f(a))
case class ParserOps[A](p: Parser[A]) {
def |[B>:A](p2: Parser[B]): Parser[B] = self.or(p,p2)
def or[B>:A](p2: => Parser[B]): Parser[B] = self.or(p,p2)
}
}
I understand that if there is a type incompatibility or missing parameters during compilation, the Scala compiler would look for a missing function that converts the non-matching type to the desired type or a variable in scope with the desired type that fits the missing parameter respectively.
If a string occurs in a place that requires a Parser[String], the string function in the above trait should be invoked to convert the string to a Parser[String].
However, I've difficulties understanding the operators and asStringParser functions. These are the questions that I have:
For the implicit operators function, why isn't there a return type?
Why is ParserOps defined as a case class and why can't the | or or function be defined in the Parsers trait itself?
What exactly is the asStringParser trying to accomplish? What is its purpose here?
Why is self needed? The book says, "Use self to explicitly disambiguate reference to the or method on the trait," but what does it mean?
I'm truly enjoying the book but the use of advanced language-specific constructs in this chapter is hindering my progress. It would be of great help if you can explain to me how this code works. I understand that the goal is to make the library "nicer" to use through operators like | and or, but don't understand how this is done.
Every method has a return type. In this case, it's ParserOps[A]. You don't have to write it out explicitly, because in this case it can be inferred automatically.
Probably because of the automatically provided ParserOps.apply-factory method in the companion object. You need fewer vals in the constructor, and you don't need the new keyword to instantiate ParserOps. It is not used in pattern matching though, so, you could do the same thing with an ordinary (non-case) class, wouldn't matter.
It's the "pimp-my-library"-pattern. It attaches methods | and or to Parser, without forcing Parser to inherit from anything. In this way, you can later declare Parser to be something like ParserState => Result[A], but you will still have methods | and or available (even though Function1[ParserState, Result[A]] does not have them).
You could put | and or directly in Parsers, but then you would have to use the syntax
|(a, b)
or(a, b)
instead of the much nicer
a | b
a or b
There are no "real operators" in Scala, everything is a method. If you want to implement a method that behaves as if it were an infix operator, you do exactly what is done in the book.

How to override an implicit conversion in my scala test?

I am working on a scala test that tests the code which uses implicit conversion methods. I don't want to use those implicit conversions and would like to mock/override them in the test. Is it possible to do that ?
implicit class Typeconverter(objA: typeA) {
def asTypeB = {
// return a typeB object
}
}
def methodA(request: typeA) {
...............
request.asTypeB
...............
}
While testing methodA, I want to mock/override "asTypeB" instead of the actual one being called.
As with any other dependency, you make m testable by passing it in.
def m(request: A)(implicit cv: A => B) = ???
Then the test can supply arbitrary conversions either explicitly or implicitly.
But an implicit inside the compiled method was resolved at compile time.
To supply a custom test version, supply a binary-compatible version of the conversion selected by implicit search. But that could be tricky and, to quote the other answer, doesn't sound like a good idea. If the implicit is neatly packaged, it might be feasible.
That doesn't sound like a good idea, but if you have a method or function with the same name and type as the original implicit in the current scope, it will override the previous one. This trick is used by e.g. rapture https://github.com/propensive/rapture/blob/dev/json-argonaut/shared/src/main/scala/rapture/json-argonaut/package.scala#L21 https://github.com/propensive/rapture/blob/dev/json-circe/shared/src/main/scala/rapture/json-circe/package.scala#L21

How to getClass implicitly

I'm writing a Scala wrapper over some Java code with a method signature like method(cl: Class[_], name: String) and many getClass methods in code looks not good:
Creator.create(getClass, "One")
Creator.create(getClass, "Two")
Creator.create(getClass, "Three")
Creator.create(getClass, "Four")
So can we somehow get enclosing class implicitly like Creator.create("some name")?
Answer 1.
In general I warmly discourage reflection. However, if you really want to do it, in Scala 2.9.1 you can use Manifest
def create[T:Manifest](name:String) = {
val klass:Class[_] = t.erasure
}
In scala 2.10 you should have a look to TypeTag.
Answer 2.
However, as I already said, the right approach would not be to use class but implicit builders
trait Builder[T]{
def build(name:String):T
}
def create[T](name:String)(implicit builder:Builder[T]) = {
builder.build(name)
}
in that way you can limit what you can create by importing only the right implicits in scope, you won't rely on reflection and you won't risk to get horrible RuntimeExceptions
Post comment answer
If your point is to avoid calling getClass at each invocation, you can do the following
def create(name:String)(implicit klass:Class[_]) {
}
And you can call it this way
implicit val klass1 = myInstance.getClass
create("hello")
create("goodbye")

Has Scala any equivalence to Haskell's undefined?

When coding in Haskell it is helpfull to define function results as "undefined" while you write the skeleton of your application. That way the executable compiles and let's you work in order parts/cases under your attention.
Is there any equivalent thing in Scala? I'd like to write something similar to:
def notAbleToWriteThisYet = undefined
def notAbleToWriteThisYet = sys.error("todo")
Also see this thread on the mailing list.
Scala 2.10.0-M1:
def notAbleToWriteThisYet = ???
(defined in Predef.scala as def ??? : Nothing = throw new NotImplementedError.)