coding style - Trick for "reusing" arguments in Haskell? -


from time time stumble on problem want express "please use last argument twice", e.g. in order write pointfree style or avoid lambda. e.g.

sqr x = x * x 

could written as

sqr = doubleargs (*)    doubleargs f x = f x x 

or consider more complicated function (taken this question):

ins x xs = zipwith (\ b -> ++ (x:b)) (inits xs) (tails xs) 

i write code pointfree if there function this:

ins x = dup (zipwith (\ b -> ++ (x:b))) inits tails      dup f f1 f2 x = f (f1 x) (f2 x) 

but can't find doubleargs or dup in hoogle, guess might miss trick or idiom here.

from control.monad:

join :: (monad m) -> m (m a) -> m join m = m >>= id  instance monad ((->) r)     return = const     m >>= f = \x -> f (m x) x 

expanding:

join :: (a -> -> b) -> (a -> b) join f = f >>= id        = \x -> id (f x) x        = \x -> f x x 

so, yeah, control.monad.join.

oh, , pointfree example, have tried using applicative notation (from control.applicative):

ins x = zipwith (\a b -> ++ (x:b)) <$> inits <*> tails 

(i don't know why people fond of a ++ (x:b) instead of a ++ [x] ++ b... it's not faster -- inliner take care of -- , latter more symmetrical! oh well)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -