A =>的惯用函数转换(B,C)至A => (C,B)

时间:2015-08-30 13:48:45

标签: scala functional-programming combinators

是否存在转换函数的惯用方法

val x: A => (B, C) = ...

val y: A => (C, B) = ...

1 个答案:

答案 0 :(得分:15)

  • 您可以使用Tuple2.swap(B, C)更改为(C, B)
  • 然后可以使用A => (B, C)A => (C, B)转换为.andThen(_.swap)

例如:

scala> val a = (i: Int) => (s"$i", i.toDouble)
a: Int => (String, Double) = <function1>

scala> val b = a.andThen(_.swap)
b: Int => (Double, String) = <function1>

scala> b(5)
res1: (Double, String) = (5.0,5)