Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose `not` with a function of arbitrary arity?

When I have some function of type like

f :: (Ord a) => a -> a -> Bool f a b = a > b 

I should like make function which wrap this function with not.

e.g. make function like this

g :: (Ord a) => a -> a -> Bool g a b = not $ f a b 

I can make combinator like

n f = (\a -> \b -> not $ f a b) 

But I don't know how.

*Main> let n f = (\a -> \b -> not $ f a b) n :: (t -> t1 -> Bool) -> t -> t1 -> Bool Main> :t n f n f :: (Ord t) => t -> t -> Bool *Main> let g = n f g :: () -> () -> Bool 

What am I doing wrong?

And bonus question how I can do this for function with more and lest parameters e.g.

t -> Bool t -> t1 -> Bool t -> t1 -> t2 -> Bool t -> t1 -> t2 -> t3 -> Bool 
like image 416
Hynek -Pichi- Vychodil Avatar asked Jan 05 '09 17:01

Hynek -Pichi- Vychodil


People also ask

What is arity in programming?

Arity (/ˈærɪti/ ( listen)) is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science. In mathematics, arity may also be named rank, but this word can have many other meanings in mathematics.

What is Fixed arity?

A fixed arity method must be called with the same number of actual parameters (also called arguments) as the number of formal parameters specified in its declaration. If the method declaration specifies two formal parameters, every call of this method must specify exactly two arguments.


1 Answers

Actually, doing arbitrary arity with type classes turns out to be incredibly easy:

module Pred where  class Predicate a where   complement :: a -> a  instance Predicate Bool where   complement = not  instance (Predicate b) => Predicate (a -> b) where   complement f = \a -> complement (f a)     -- if you want to be mysterious, then   -- complement = (complement .)   -- also works  ge :: Ord a => a -> a -> Bool ge = complement (<) 

Thanks for pointing out this cool problem. I love Haskell.

like image 68
Norman Ramsey Avatar answered Oct 06 '22 00:10

Norman Ramsey