I want to implement Option Monad in SML, so I can use them the same way they can be used in haskell. What I did, does not work.
infix 1 >>=
signature MONAD =
sig
    type 'a m 
    val return : 'a -> 'a m 
    val >>= : 'a m * ('a -> 'b m) -> 'b m 
end;
structure OptionM : MONAD =
struct
    type 'a m = 'a option
    val return = SOME
    fun x >>= k = Option.mapPartial k x
end;
val x = OptionM.return 3;
x (OptionM.>>=) (fn y => NONE);
Result:
stdIn:141.1-141.31 Error: operator is not a function [tycon mismatch] 
operator: int OptionM.m
in expression:
x OptionM.>>=
What can I do to make the last line work?
Unlike in Haskell, qualified infix operators (such as A.+ or Option.>>=) are not infix in SML. You need to use them unqualified, e.g. by either opening the module or by rebinding it locally.
Btw, you probably want to define >>= as right-associative, i.e., use infixr.
Also, SML has stricter precedence rules than Haskell. That will make it somewhat more tedious to chain several uses of >>= with lambdas, because you have to parenthesise each fn on the right:
foo >>= (fn x => bar >>= (fn y => baz >>= (fn z => boo)))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With