[英]Translating custom type from F# to Scala
I started to learn Scala out of interest, and I decided that I want to translate Scott Wlaschin's parser combinators package from F# to Scala, so the stuff would really settle in. The whole point of Scott's package is to use monads practically everywhere, so I'm also looking at this as a chance to understand monads even further.出于兴趣,我开始学习 Scala,我决定将 Scott Wlaschin 的parser combinators包从 F# 翻译成 Scala,这样这些东西就会真正安顿下来。 Scott 的包的重点是几乎在任何地方都使用 monad,所以我我也将其视为进一步了解 monad 的机会。
In one of the early slides, he defines the type type Parser<'a> = Parser of (string -> Result<'a * string>)
, where:在早期的一张幻灯片中,他定义了类型type Parser<'a> = Parser of (string -> Result<'a * string>)
,其中:
type Result<'a> =
| Success of 'a
| Failure of string
The subtle thing in this definition is the coupling between 'a
on both sides of the equation of Parser<'a>
.这个定义中的微妙之处在于Parser<'a>
等式两边的'a
之间的耦合。
In any case, how can I translate the above statements to Scala, while preserving the subtlety that I mentioned?无论如何,如何将上述语句转换为 Scala,同时保留我提到的微妙之处?
For the first one I thought of this:对于第一个我想到了这个:
type ParserType[T] = String => Result[(T, String)]
and for the second one (which is a choice type) I thought of this:对于第二个(这是一种选择类型),我想到了这一点:
sealed trait Result[T]
case class Success[T](result: T) extends Result[T]
case class Failure[T](msg: String) extends Result[T]
but, it seems stupid to use [T]
in Failure
, since it doesn't use T
at all.但是,在Failure
使用[T]
似乎很愚蠢,因为它根本不使用T
。 Is there some syntax which can more closely resemble the F# syntax?是否有一些语法可以更接近于 F# 语法?
Take a look at the new right biased Either
in Scala 2.12 (baring that, there was a Xor
data type in the Cats lib.) However, to answer your question directly:看看 Scala 2.12 中新的偏右Either
(除此之外,Cats 库中有一个Xor
数据类型。)但是,直接回答你的问题:
sealed trait Result[+T]
case class Success[T](result: T) extends Result[T]
case class Failure(msg: String) extends Result[Nothing]
this takes advantage of type covariance.这利用了类型协方差。 Any Failure
here can be used with any Success
.此处的 Any Failure
可与任何Success
一起使用。 Note, this doesn't handle map
or flatMap
concerns.请注意,这不处理map
或flatMap
问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.