<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body text="#000000" bgcolor="#FFFFFF">
<br>
<div class="moz-cite-prefix">On 2017-05-07 00:23, Jon Purdy wrote:<br>
</div>
<blockquote
cite="mid:CAE3FWBvM5jfP1JysORcKUZEfMHB+izV4fCpEooqebiD_wPZP3Q@mail.gmail.com"
type="cite">
<div dir="ltr">I’ve wanted this before as well. Maybe we should
throw a newtype at it?
<div><br>
</div>
<div>newtype LeftBiased a = LeftBiased [a]</div>
<div>instance Alternative (LeftBiased a) where</div>
<div> empty = []</div>
<div> [] <|> b = b</div>
<div> a <|> _ = a</div>
<div><br>
</div>
<div>
<div>newtype RightBiased a = RightBiased [a]</div>
<div>instance Alternative (RightBiased a) where</div>
<div> empty = []</div>
<div> a <|> [] = a</div>
<div> _ <|> b = b</div>
</div>
<div><br>
</div>
</div>
</blockquote>
<p>You forgot the fun wrapping and unwrapping. But no matter. Let's
generalize!</p>
<pre> class Neutral a where
neutral :: a
isNeutral :: a -> Bool</pre>
<div>
<pre> instance Neutral a => Alternative (LeftBiased a) where
empty = LeftBiased neutral
(LeftBiased a) <|> (LeftBiased b) = LeftBiased $ if isNeutral a then b else a</pre>
</div>
<div>
<pre> instance Neutral a => Alternative (RightBiased a) where
empty = RightBiased neutral
(RightBiased a) <|> (RightBiased b) = RightBiased $ if isNeutral b then a else b</pre>
</div>
<p>Why?</p>
<pre> type AllRight e a = LeftBiased (Either e a)
type AnyRight e a = RightBiased (Either e a)
instance Neutral a => Neutral (AllRight e a) where
neutral = Right $ LeftBiased neutral
isNeutral = fmap isRight
instance Neutral e => Neutral (AnyRight e a) where
neutral = Left $ RightBiased neutral
isNeutral = fmap isLeft</pre>
<p>Is this a bit silly? Yes. My actual goal is to show that these
concepts are bigger than they might appear, and how painful all
those wrappers are. This is to advertise my language extension
from my separate thread. And also because it's silly fun. Mostly
that.</p>
<p><br>
</p>
<blockquote
cite="mid:CAE3FWBvM5jfP1JysORcKUZEfMHB+izV4fCpEooqebiD_wPZP3Q@mail.gmail.com"
type="cite">
<div dir="ltr">
<div>newtype Unbiased a = Unbiased (Maybe a)</div>
<div>instance (Monoid m) => Alternative (Unbiased m) where</div>
<div> empty = Nothing</div>
<div> Just a <|> Just b = Just (a <> b)</div>
<div> _ <|> Just b = Just b</div>
<div> Just a <|> _ = Just a</div>
<div> _ <|> _ = Nothing</div>
</div>
</blockquote>
<p>Mh, that's just <tt>liftA2 (<>) a b <|> a <|>
b</tt> in terms of the regular instance. Now that is easy to
generalize – just don't use it for lists.<br>
</p>
Cheers,<br>
MarLinn<br>
</body>
</html>