scalapuzzlers / scalapuzzlers.github.com

Github Pages behind scalapuzzlers.com
www.scalapuzzlers.com
161 stars 53 forks source link

Sieve of Stefan Zeiger #144

Closed som-snytt closed 8 years ago

som-snytt commented 8 years ago

In time for Scala World, I guess.

Welcome to Scala 2.12.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> class C[A] {
     |   var a: A = _
     |   def f(seq: Seq[Any])(implicit tag: reflect.ClassTag[A]): Seq[A] =
     |     seq.collect { case tag(t) => t }
     | }
defined class C

scala> val c = new C[Double]
c: C[Double] = C@78a515e4

scala> c.a
res0: Double = 0.0

scala> c.f(List(1, c.a, "s"))
res1: Seq[Double] = List()

scala> c.f(List(1, 0.0, "s"))
res2: Seq[Double] = List(0.0)

https://github.com/scala/scala/pull/5347#issuecomment-242347551

demobox commented 8 years ago

Thanks @som-snytt! Wow, sneakily packaged up there! ;-)

Looking at the original example in #5347, I wonder to what extent this is the related to http://scalapuzzlers.com/#pzzlr-029?

It's based on a specific overloaded method so certainly isn't exactly the same, but I wonder whether the underlying cause may be similar? Haven't looked into it in much detail yet, I hasten to add...

som-snytt commented 8 years ago

How do you remember all those past puzzlers? Yes, both turn on broken = _ (as sjrd calls it). Is this more compelling as tag.unapply(a) or case _: A etc?

Maybe you'll like this better:

println(Some("foo").asInstanceOf[Option[Integer]].get)

https://twitter.com/Blaisorblade/status/768120393769086976

I don't use twitter anymore, of course.

demobox commented 8 years ago

How do you remember all those past puzzlers?

Actually, I'm just going through them to see how Dotty differs ;-) But I liked this case specifically because it shows how (in the Pick An Int puzzler) inheritance can nullify expected type constraints, and that the lack of an obvious "base type" for AnyVal (inherited-and-not-addressed from Java) is a bit of a hole in the Scala type system.

So a great example of a puzzler that truly indicates the challenge of unifying functional and OO on top of the JVM, if you ask me ;-)

som-snytt commented 8 years ago

What if it means there are no more puzzlers?