简体   繁体   English

Scala相当于Haskell第一和第二

[英]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: Haskell具有非常方便的函数,称为firstsecond ,它们将函数应用于一对中的一个元素:

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

Are such functions defined in the standard Scala libraries? 这些功能是否在标准Scala库中定义?

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? 这些功能是否在标准Scala库中定义?

Nope. 不。 This isn't something that comes up so often in Scala that it warrants being in the standard library. 这不是在Scala中经常出现的,以至于保证在标准库中。 It is also very difficult to generalize to tuples of any arity without an explosive amount of code (or macro). 如果没有大量的代码(或宏),很难将其归纳为任何Arue元组。

Haskell's Arrows ( first and second are among them) are implemented in Scalaz: Haskell的Arrows( firstsecond在其中)在Scalaz中实现:

Scalaz source Scalaz来源

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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