python - simplifying maybe Monad -


i trying understand maybe monad of examples saw used language-specific feature. ensure have gotten conceptually right thought of writing generic implementation. below came with.

can tell if have gotten conceptually right? there better way generalize it?

def f():     return 2  def g():     return 4  def h():     return 7  def i():     return none  def bind(val, func):     if val none:         return none     else:         return(func())  unit = 0  >>> bind(bind(bind(unit,f),i),h) #returns nothing >>> bind(bind(bind(unit,f),g),h) #returns value >>>7  

what if wanted add values these functions , abort if of null; suggestion?

you're close, signature of bind is

m -> (a -> m b) -> m b 

so it's "unwrapping" m , passing contained value next function. have

m -> ( () -> m b) -> m b 

since you're ignoring val bind gets, should have

def bind(val, func):     if val none:         return none     else:         return(func(val)) 

this equivalent >>= in haskell. had before >> should implemented as

# "ignore" bind def ibind(val, func):     bind(val, lambda _ : func()) 

which happily throws away value bind passes it.

to take further, you'd have introduce class

class maybe():     def __init__(v):         self.val = v         self.isnothing = false nothing = maybe(none) nothing.isnothing = true  def bind(val, func):     if val.isnothing:         return nothing     else:         return(func(val.val)) 

Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -