5

A function which zips a list onto itself can be defined as:

let adjacent1 l = zip l $ tail l

This works, but I'd like to define it in pointfree style. To do this, I define a function dollarize:

let dollarize f1 f2 x = f1 x $ f2 x
let adjacent1 = dollarize zip tail

This works, but obviously I'd rather not define my own higher-order functions. Is there a way to find the standard equivalent of dollarize, assuming it exists? And if not, where are the functions of this sort which exist to combine functions?

3 Answers 3

11

The pointfree tool can do this for you automagically.

$ pointfree "\l -> zip l (tail l)"
ap zip tail
$ pointfree "\f1 f2 x -> f1 x $ f2 x"
ap
Sign up to request clarification or add additional context in comments.

1 Comment

If you are a regular IRC user, the lambdabot of #haskell can do the same thing. Just query it @pl \l -> zip l (tail l) and you'll get the same answer.
6

How about using the Applicative instance of (->) a?

Prelude Control.Applicative> :t zip <*> tail
zip  <*> tail :: [a] -> [(a, a)]
Prelude Control.Applicative> zip <*> tail $ [1 .. 4]
[(1,2),(2,3),(3,4)]

short and sweet.

5 Comments

Yes, just checked that, wasn't sure.
It's obvious if you remember that <$> on functions is just function composition, and composing with id obviously does nothing. Also worth mentioning that <*> is the S combinator from SKI calculus.
Which would help if I knew SKI calculus ;)
Yes, this is the kind of thing I would like to do, but how would I find <*>, if I don't know about it?
@Marcin: Normally, I recommend Hoogle. However, it won't find the answer in this case, since it treats the function arrow (->) specially, so it never finds functions which rely on using (a ->) as a monad/applicative, so searching for f (b -> c) -> f b -> f c works, but not (a -> b -> c) -> (a -> b) -> a -> c.
3

Accoring to @Daniel Fischer's answer. Also your can use monad instance of (->) a:

Prelude Control.Monad.Instances> let adjacent1 = tail >>= flip zip
Prelude Control.Monad.Instances> adjacent1 [1..4]
[(1,2),(2,3),(3,4)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.