Mohan Mohan - 8 months ago 71
Scala Question

Scala equivalent of Haskell first and second

Haskell has very convenient functions called

which apply a function to one element of a pair:

first fn (a,b) = (fn a, b)
second fn (a,b) = (a, fn b)

Are such functions defined in the standard Scala libraries?

Edit: I know it's easy to define them, but where possible it's cleaner to use standard functions with standard names…

def first[A, B, X](fn: A => X)(pair: (A, B)): (X, B) = (fn(pair._1), pair._2)
def second[A, B, X](fn: B => X)(pair: (A, B)): (A, X) = (pair._1, fn(pair._2))


Haskell's Arrows (first and second are among them) are implemented in Scalaz:

Scalaz source

Some examples

While it's technically not a standard library it's stable and seems to be well maintained.


Syntax is a bit cumbersome though (maybe there is another way?):

import scalaz._
import Scalaz._

val f = (x: Int) => x + 1
val g = f.second[String]
g("1", 2) //> ("1", 3)

// or with type inference

f second ("1", 2) //> ("1", 3)