Haskell - Overwriting parameters causes unexpected behaviours -
i wrote simple function
somefunc list elem = list <- elem:elem:elem:list return elem
now, when i'm using it, i'm getting output this
*main> somefunc [] 'a' "aaa"
despite fact, function has no practical use, why happen? why editing list have effect in elem
? , how assign new value list
avoiding situation?
note function de-sugared this:
somefunc :: [b] -> b -> [b] somefunc list elem = (elem:elem:elem:list) >>= \list -> return elem
now note list
in \list -> return elem
different input list
pass function.
now see how monad instance list defined:
instance monad [] return x = [x] xs >>= f = concat (map f xs) fail _ = []
so, code translated form finally:
somefunc list elem = concat $ map (\list -> return elem) (elem:elem:elem:list)
now can understand why getting output ?
somefunc [] 'a'
applied this:
concat $ map (\list -> return 'a') ('a':'a':'a':[]) concat $ [['a'],['a'],['a']] 'a':'a':'a':[] "aaa"
Comments
Post a Comment