简体   繁体   中英

Scala equivalent of Haskell first and second

Haskell has very convenient functions called first and second 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))

Are such functions defined in the standard Scala libraries?

Nope. This isn't something that comes up so often in Scala that it warrants being in the standard library. It is also very difficult to generalize to tuples of any arity without an explosive amount of code (or macro).

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM