Haskell或Scala中是否存在Either
的标准专业化,使Left
和Right
中包含的类型相同?
在Haskell中,我想要这样的东西:
data SpecializedEither a = Left a | Right a
这也可以被视为Maybe
的轻微概括,使Nothing
保持一个值。
编辑:Ganesh提出了一个非常好的观点,即不能为此类型定义Monad实例。有没有更好的方法来做我想做的事情?
答案 0 :(得分:11)
e
只要Monoid
是instance Monoid e => Monad ((,) e) where
return a = (mempty, a)
(e1, a) >>= f = let (e2, b) = f a in (e1 <> e2, b)
Either a a
由于(Bool, a)
和Monad
是同构的(以两种方式),我们只要为Monoid
选择Bool
就会获得Monoid
个实例。有两个(实际上是四个,见评论),如Left
s,&#34;和&#34;类型和&#34;或&#34;类型。从本质上讲,这种选择最终会决定您的Right
或Right
方面是&#34;默认&#34;。如果Left
是默认值(因此data Either1 a = Left1 a | Right1 a
get1 :: Either1 a -> a
get1 (Left1 a) = a
get1 (Right1 a) = a
instance Monad Either1 where
return = Right1
x >>= f = case (x, f (get1 x)) of
(Right1 _, Right1 b) -> Right1 b
(Right1 _, Left1 b) -> Left1 b
(Left1 _, y ) -> Left1 (get1 y)
会覆盖它),那么我们得到
{{1}}
答案 1 :(得分:1)
怎么样:
type Foo[T] = Either[T, T]
val x: Foo[String] = Right("")
// Foo[String] = Right()