Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want to do it in a single <code>foldr</code>, we can exploit the fact that <code>Ord a =&gt; Ord (Maybe a)</code>, that is, any ordering on <code>a</code> can be extended to an ordering on <code>Maybe a</code>.</p> <p>We also have <code>Just x &gt; Nothing</code>, for all <code>x :: Ord a =&gt; a</code>.</p> <pre><code>mymax :: (Ord a) =&gt; [a] -&gt; Maybe a mymax = foldr (\x b -&gt; let x' = Just x in if x' &gt; b then x' else b) Nothing -- equivalently mymax = foldr (\x b -&gt; let x' = Just x in max x' b) Nothing mymax = foldr (\x' b -&gt; max x' b) Nothing . map (\x -&gt; Just x) mymax = foldr max Nothing . map Just </code></pre> <p>If we want to do minimum, we'll have to do it a bit differently, since <code>Nothing</code> is the lower bound for the type <code>Ord a =&gt; Maybe a</code>, which means that <code>foldr min Nothing . map Just == const Nothing</code>, which isn't useful. </p> <pre><code>mymin :: (Ord a) =&gt; [a] -&gt; Maybe a mymin = foldr (\x b -&gt; case b of Nothing -&gt; Just x Just y -&gt; Just (min x y) ) Nothing -- which is equivalent to mymin = foldr (\x b -&gt; Just $ case b of Nothing -&gt; x Just y -&gt; min x y ) Nothing mymin = foldr (\x b -&gt; Just $ maybe x (min x) b) Nothing mymin = foldr (\x -&gt; Just . maybe x (min x)) Nothing </code></pre> <p>Honestly, though, I think pattern matching makes solutions a lot clearer</p> <pre><code>mymax [] = Nothing mymax (a:as) = Just $ foldr max a as mymin [] = Nothing mymin (a:as) = Just $ foldr min a as </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload