[Solved] State Monad in Rust?

If we squint, Rust/Option == Maybe Monad.
Rust/Result == Either Monad.

Is there any hnice way to get teh 'State Monad' in Rust?

1 Like

I do not see any monad in rust.

I do not see a bind function…

1 Like

Okay, at least for Option I found binds equivalent: Option::and_then.

Result has this method as well.

But I think you'll have to implement it on your own for "state".

1 Like

A Monad trait is currently impossible to express in rust's type system. This is because rust doesn't support higher kinded types.

In haskell, the bind function has type:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

Here, m is a type constructor rather than a type, and has kind * - > * rather than *. The Monad typeclass has kind (* -> *) -> Constraint . Rust's traits can only be * -> Constraint.

Lots of rust libraries contain parallels to >>=, >>, fmap, <|>, and such, but there's no monad, functor, or alternative traits to unify all these into something you can use as a constraint. The naming generally goes like this:

Haskell Rust
>>= and_then
>> and
`< >`
fmap map

You can see these in Result, Option, and Iterator from the standard library, and probably a whole bunch more that I'm forgetting.

There has been discussion of adding higher kinded types to rust before, but I don't think it's likely to happen soon.

3 Likes

@NobbZ , @Benjamin-L : Thanks! Marking question as resolved, as it's unlikely we can push this any further.

1 Like

… at least until HRTBs land, perhaps this year or next.

1 Like

I believe that you might have the wrong terminology, HRTB refers to variable lifetime syntax for<'a> Type<'a>, and it's stable. Perhaps you're referring to specialization? I'm not versed (at all) in purely functional programming languages like (I believe these are applicable) F# or Haskel so perhaps I'm wrong.

3 Likes

You are probably correct. I'm just back from a concert and saw the post and stupidly added to the confusion. Rather than HRTB, I probably should have said HKT (higher kinded types). There is a lot of ongoing work on the compiler, in Polonius and Chalk, that is extending Rust in ways that permit closer alignment with functional programming.

3 Likes