F# computation expression for exception monad -


i'm implementing exception monad in f#. first took ml approach, works:

module exceptionmonad =   type exception_ = string   type 'a t = raise of exception_ | return of 'a    let return' t = return t   let raise' e = raise e   let (>>=) m k =     match m     | raise e -> raise e     | return -> k  module testexceptionmonad =   open exceptionmonad    let test_exception_monad =     begin       return' 1 >>= fun ->       return' 0 >>= fun b ->       if b = 0         raise' "divide zero"         else return' (a / b)     end (* => raise' "divide zero" *) 

now i'm trying use f# computation expression instead:

type exception_ = string type 'a exception_monad = raise of exception_ | return of 'a type exceptionmonad() =     member x.bind(m, k) =         match m         | raise e -> raise e         | return -> k     member x.return(t) = return t     member x.zero() = return 0  module testexceptionmonad =     let monad = new exceptionmonad()      let test_exception_monad =         monad {             let! = return 1 in             let! b = return 0 in             if b = 0                 raise "divide zero"             else                 return (a / b)         } (* => raise "divide zero" *) 

but f# complaining expression raise "divide zero" of type unit. not true, guess there's code generation going on behind scenes, , error refers that. i'm not sure why x.zero() needed, required compiler.

in f# computation expressions, when have "monadic value" want return computation, need use return! construct:

if b = 0 return! raise "divide zero" else return (a / b) 

to support this, need add returnfrom computation builder:

member x.returnfrom(c) = c 

that said, implementing computation builder exceptions exercise if you're trying understand how computation builders work in f#. unless have reasons wanting it, not recommend in practice. f# has direct support exceptions can use without special syntax works in of situations, there no need replace more complicated way of doing same thing.

if you're looking input validation (as opposed ordinary exception handling), there nice f# project implements computation chessie, again - more of input validation exception handling.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -