Skip to content

Signal as a Monad #413

@fosskers

Description

@fosskers

Signals are clearly Applicative Functors since:

instance Functor Signal where
   fmap = lift

instance Applicative Signal where
   pure = constant
   (<*>) = (~)

Before I had even discovered () I noticed the Applicative nature of Signals and was wondering how to implement the equivalent of (<*>) in Elm. Eventually I found () and thought it cool that it was native Elm. Upon closer inspection though we find it the opposite of Haskell, with (~) written in terms of lift* and not the other way around:

-- Elm.
(~) : Signal (a -> b) -> Signal a -> Signal b
f ~ a = lift2 (\f' a' -> f' a') f a

-- Pattern-matched / Haskell-like?
(~) : Signal (a -> b) -> Signal a -> Signal b
Signal f ~ a = lift f a

As far as I can tell, Signals are also Monads. If Signal is pattern-matchable, we could do the following, like the above:

(>>=) : Signal a -> (a -> Signal b) -> Signal b
Signal a >>= f = f a

(>>) : Signal a -> Signal b -> Signal b
a >> b = a >>= \_ -> b
-- And so on.

If it isn't pattern-matchable, could something be hacked in Native.Signal just like the Applicative definition? I've found a few times I've wanted Monadic code. Or will Applicative always be better with Signals? Am I missing some key Elm design choice?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions