Scala 中隐式与幺半群的简单组合
Simple composition of implicits with Monoids in Scala
我有以下特点:
import scalaz.Monoid
trait Mapper[M, R] {
def map(m: M): R
}
object Mapper {
@inline implicit def listMapper[M, R]
(implicit mapper: Mapper[M, R], s: Monoid[R]): Mapper[List[M], R] =
(xs: List[M]) => xs. foldLeft(s.zero)((r, m) => s.append(r, mapper.map(m)))
}
现在我想列出 R = String
的映射器,它产生类似于以下内容的 [mapped_string1, mapped_string2]
或
$%%""mapped_string1, mapped_string2""%%$
.
问题是以下幺半群实现不起作用:
implicit val myStringMonoid: Monoid[String] = new Monoid[String] {
override def zero = ""
override def append(f1: String, f2: => String) =
if (f1.isEmpty) f2
else if(f2.isEmpty) f1
else f1 + ", " + f2
}
所以下面一行
println(implicitly[Mapper[List[String], String]].map(List("mapped_string1", "mapped_string2")))
打印 mapped_string1, mapped_string2
不带尖括号.
这种情况的解决方案是什么?也许只是幺半群确实很适合我的需要。也许我需要另一个抽象层次。
我的意思是如何在 foldLeft
完成后通常添加一些要调用的额外操作?不与 String
或任何特定类型耦合。
implicit def listMapper[M, R]
(implicit mapper: Mapper[M, R], s: Monoid[R]): Mapper[List[M], R] = ???
意味着如果你有Mapper[M, R]
那么你就有Mapper[List[M], R]
。但是要完成这项工作,您应该有一些初始 Mapper[M, R]
.
所以如果你想要Mapper[List[String], String]
你应该添加例如
implicit def stringMapper: Mapper[String, String] = s => s
然后这会产生
println(implicitly[Mapper[List[String], String]].map(List("mapped_string1", "mapped_string2")))
//mapped_string1, mapped_string2
def addBrackets(s: String, openBracket: String, closingBracket: String) =
openBracket + s + closingBracket
val s = implicitly[Mapper[List[String], String]].map(List("mapped_string1", "mapped_string2"))
println(addBrackets(s, "[", "]"))
//[mapped_string1, mapped_string2]
否则你可以改变
implicit val myStringMonoid: Monoid[String] = new Monoid[String] {
override def zero = ""
override def append(f1: String, f2: => String): String =
if (f1.isEmpty) f2
else if(f2.isEmpty) f1
else f1 + f2 // without ", "
}
然后
val l = "[" ::
List("mapped_string1", "mapped_string2")
.flatMap(s => List(", ", s))
.tail ::: List("]")
println(implicitly[Mapper[List[String], String]].map(l))
//[mapped_string1, mapped_string2]