Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SML Option Monad (bind operator not working)

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?

like image 387
infal Avatar asked Mar 11 '23 21:03

infal


1 Answers

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)))
like image 159
Andreas Rossberg Avatar answered Mar 23 '23 16:03

Andreas Rossberg