Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Function to determine the arity of functions?

Tags:

Is it possible to write a function arity :: a -> Integer to determine the arity of arbitrary functions, such that

> arity map 2 > arity foldr 3 > arity id 1 > arity "hello" 0 

?

like image 303
Frank S. Thomas Avatar asked Dec 03 '11 16:12

Frank S. Thomas


People also ask

What is arity in Haskell?

1. I define arity as the number of times you can apply an argument to a term.

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?

Fixed arity function is the most popular kind present in almos tall programming languages. Fixed arity function must be called with the same number of arguments as the number of parameters specified in its declaration. Definite arity function must be called with a finite number of arguments.

What is a function in Haskell?

Haskell - Functions. Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration. Function declaration consists of the function name and its argument list along with its output.

What is a lambda expression in Haskell?

We sometimes have to write a function that is going to be used only once, throughout the entire lifespan of an application. To deal with this kind of situations, Haskell developers use another anonymous block known as lambda expression or lambda function. A function without having a definition is called a lambda function.

Which two functions can be compared for equality in Haskell?

That means that any two functions can be compared for equality. Most notably, in Haskell, functions are not in the Eq typeclass (in general). Not any two functions can be compared for equality in Haskell.

What is recursion in Haskell?

Recursion is a situation where a function calls itself repeatedly. Haskell does not provide any facility of looping any expression for more than once. Instead, Haskell wants you to break your entire functionality into a collection of different functions and use recursion technique to implement your functionality.


1 Answers

Yes, it can be done very, very easily:

arity :: (a -> b) -> Int arity = const 1 

Rationale: If it is a function, you can apply it to exactly 1 argument. Note that haskell syntax makes it impossible to apply to 0, 2 or more arguments as f a b is really (f a) b, i.e. not f applied to a and b, but (f applied to a) applied to b. The result may, of course, be another function that can be applied again, and so forth.

Sounds stupid, but is nothing but the truth.

like image 159
Ingo Avatar answered Sep 26 '22 05:09

Ingo