简体   繁体   中英

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.

In one of the early slides, he defines the type type Parser<'a> = Parser of (string -> Result<'a * string>) , where:

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> .

In any case, how can I translate the above statements to Scala, while preserving the subtlety that I mentioned?

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. Is there some syntax which can more closely resemble the F# syntax?

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:

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 . Note, this doesn't handle map or flatMap concerns.

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