[Haskell-cafe] how do I avoid excessive constructor application?

Stefan Holdermans sholderm at students.cs.uu.nl
Wed Mar 2 09:36:15 EST 2005


>   fun::(a->a1)->(Either a b)->Either a1 b
>   fun f (Left x) = Left (f x)
>   fun _ r@(Right x)= Right x
> I'd like to avoid the destruction and construction in the third line 
> by replacing the right hand side with r.  However, the typechecker
> then claims my type is wrong.  How do I fix that?

You can't. At the left-hand side r has type Either a b; at the 
right-hand side an expression of type Either a1 b is required, so you 
can't just supply b.

You could do something like

f            :: (a -> c) -> Either a b -> Either c b
f g (Left a) =  Left (g a)
f g x        =  coerceRight x

coerceRight           :: Either a b -> Either c b
coerceRight (Right b) =  Right b

but I'm not too sure whether that's more elegant.



More information about the Haskell-Cafe mailing list