How to build 'missing' complex functions in Haskell

121 views Asked by At

How should I aprroach situations when I know type of needed function but it is not defined yet? I suspect function I'm looking for is easily composable from others, but I don't know where to start looking.

Prelude> :hoogle (b->b->c)->(a->b)->(a->b)->a->a->c
No results found

To be more specific, I have (b->b->c) function at hand but I need to process (lift maybe?) the arguments first. Can hoogle find functions with arguments in different order than specified?

This is close to what I need, but I want to apply different function to each argument.

Prelude Data.Function> :t on
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
2

There are 2 answers

0
Manuel Eberl On BEST ANSWER

Seeing as your question asked how this function can be composed from other functions, I would like to point out that you can write it as:

import Control.Arrow
on2 :: (b -> b -> c) -> (a -> b) -> (a -> b) -> a -> a -> c
on2 f g h = curry (uncurry f . (g *** h))

However, the straightforward definition suggested by bheklilr is obviously just as concise and much more readable for people who are not used to working with Arrows.

And, yes, as far as I know, Hoogle does also search for functions in which the order of argument types you specified is permuted.

1
bheklilr On

If you don't find it on hoogle, it probably isn't already defined. Feel free to define your own as

on2 :: (b1 -> b2 -> c) -> (a1 -> b1) -> (a2 -> b2) -> a1 -> a2 -> c
on2 f p1 p2 a1 a2 = f (p1 a1) (p2 a2)

But this would lead to expressions like

on2 zip init tail xs ys

Instead of just

zip (init xs) (tail ys)

So I don't know if it'd really save you much room.