Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the name of this monad-like functional programming pattern?
    primarykey
    data
    text
    <p>I have occasionally encountered a pattern in code which resembles a monad but does not keep a consistent type across <code>&gt;&gt;=</code>.</p> <p>Here is the simplest example I could come up with:</p> <p>(First some type-level booleans:</p> <pre><code>data TyT = TyT data TyF = TyF class TyOr a b c | a b -&gt; c instance TyOr TyF TyF TyF -- rest similarly </code></pre> <p>)</p> <p>Now here is our "monad" type constructor:</p> <pre><code>data Marked p a = Marked a deriving (Show) </code></pre> <p>For a given <code>p</code>, <code>Marked p</code> is a <code>* -&gt; *</code> which acts very much like <code>m</code> in a monad, but different, as occurs next, when we define "bind":</p> <pre><code>(&gt;&gt;%) :: (TyOr p q r) =&gt; Marked p a -&gt; (a -&gt; Marked q b) -&gt; Marked r b (Marked x) &gt;&gt;% f = Marked y where Marked y = f x </code></pre> <p>What's different here is that the result of <code>&gt;&gt;%</code> has a different type constructor than the arguments. Other than that it's basically a monad.</p> <p>We could use it like this:</p> <pre><code>a :: Marked TyF Int a = Marked 5 f :: Int -&gt; Marked TyT Int f x = Marked (x + 1) ghci&gt; a &gt;&gt;% f Marked 6 ghci&gt; :t a &gt;&gt;% f a &gt;&gt;% f :: Marked TyT Int </code></pre> <p>(This was inspired by <a href="https://stackoverflow.com/questions/7131027/is-with-monadic/7131291#7131291">outis's observation that Python's "with" can't be a monad because it changes the type</a>, but I've seen it in other (simpler) ways too).</p>
    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.
 

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