Mohan - 7 months ago 67

Scala Question

Haskell has very convenient functions called

`first`

`second`

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

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

Are such functions defined in the standard Scala libraries?

`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))

Answer

Haskell's Arrows (`first`

and `second`

are among them) are implemented in Scalaz:

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

**UPDATE**

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)
```