Skip to content

Instantly share code, notes, and snippets.

View tpolecat's full-sized avatar
🔥
Dijkstra would not have liked this.

Rob Norris tpolecat

🔥
Dijkstra would not have liked this.
View GitHub Profile
@tpolecat
tpolecat / gist:7401433
Last active August 29, 2020 08:00
set is not a functor mkay
scala> case class Bad(a: Int) { override def equals(a:Any) = true }
scala> val f = (n:Int) => Bad(n)
scala> val g = (b:Bad) => b.a
...
scala> Set(1,2,3).map(f andThen g)
res2: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> Set(1,2,3).map(f).map(g)
// Where the hell does B come from? Looks like a type variable is escaping.
scala> Left(1).disjunction
res14: scalaz.\/[Int,B] = -\/(1)
// It's not Nothing
scala> Left(1).disjunction : (Int \/ Nothing)
<console>:17: error: type mismatch;
found : scalaz.\/[Int,B]
name := "just-scalaz"
version := "0.1"
scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
"org.scalaz" % "scalaz-core_2.10" % "7.0.3",
"org.scalaz" % "scalaz-effect_2.10" % "7.0.3"
)
// Scala widens Char to Int here, rather than unifying to AnyVal
scala> List('a', 1)
res7: List[Int] = List(97, 1)
// And even widens to Double. Nutty
scala> List('a', 3.14)
res14: List[Double] = List(97.0, 3.14)
@tpolecat
tpolecat / gist:7107143
Last active December 26, 2015 06:19
Due to an oversight in the implementation it's possible for function values to have a vararg signature, leading to various kinds of hilarity. Retronym confirms that this is a bug (see tweeties at https://twitter.com/tpolecat/status/392747549733306368)
// Eta-expansion turns A* to Seq[A]
scala> def foo(ns:Int*) = ns.sum
foo: (ns: Int*)Int
scala> foo(1,2,3)
res0: Int = 6
scala> val foov = foo _
foov: Seq[Int] => Int = <function1>
@tpolecat
tpolecat / gist:6724500
Created September 27, 2013 05:23
How can you do this consistently? I don't think it is possible with universal equality.
class Animal(val name: String) {
override def equals(a: Any): Boolean =
a match {
case a: Animal if a.name == name => true
case _ => false
}
}
class Cat(name: String, val color: String) extends Animal(name) {
override def equals(a: Any): Boolean =
// rank 1
type num[a] = (a => a) => a => a
def zero[a]: num[a] = f => x => x
def succ[a](n: num[a]): num[a] = f => x => f(n(f)(x))
def eval(n: num[Int]): Int = n(_ + 1)(0)
// rank 2
def exists[A](as: List[A], f: A => Boolean): Boolean =
as match {
case Nil => false
case a :: as0 => if (f(a)) true else exists(as0, f)
}
def forall[A](as: List[A], f: A => Boolean): Boolean =
!exists(as, (a: A) => !f(a))
scala> def a: Any = List(1,2,3).map(x => x + 1)
a: Any
scala> def b: Any = List(1,2,3).map(x => return x + 1)
b: Any
scala> a
res1: Any = List(2, 3, 4)
scala> b
scala> def foo[A[_]] = 1
foo: [A[_]]=> Int
scala> foo[List]
res11: Int = 1
scala> foo[Int]
<console>:24: error: Int takes no type parameters, expected: one
foo[Int]
^