Last active
September 12, 2016 22:56
-
-
Save n4to4/d91aa446cfd85011620b2381eb3c9af3 to your computer and use it in GitHub Desktop.
Scala equivalent of Haskell first and second
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz._, Scalaz._ | |
object Main extends App { | |
// Scala equivalent of Haskell first and second | |
// http://stackoverflow.com/questions/39457088/scala-equivalent-of-haskell-first-and-second | |
type T2 = Tuple2[Int, Int] | |
val f = (n: Int) => n + 1 | |
val g = (n: Int) => n * 100 | |
def stdFirst[A, B, X](fn: A => X)(pair: (A, B)): (X, B) = (fn(pair._1), pair._2) | |
def stdSecond[A, B, X](fn: B => X)(pair: (A, B)): (A, X) = (pair._1, fn(pair._2)) | |
assert { (stdFirst(f)((1, 2))) == ((2, 2): T2) } | |
assert { (stdSecond(g)((1, 2))) == ((1, 200): T2) } | |
//---------------------------------------------------------------------- | |
// first[A, B, C](fa: =>:[A, B]): =>:[(A, C), (B, C)] | |
// second[A, B, C](f: =>:[A, B]): =>:[(C, A), (C, B)] | |
assert { f.first((1, 2)) === ((2, 2): T2) } | |
assert { g.second((1, 2)) === ((1, 200): T2) } | |
assert { (f *** g)((1, 2)) === ((2, 200): T2) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment