A binary function in Haskell is a function that takes two arguments and returns a result. In Haskell, functions are inherently curried, meaning a binary function can be thought of as a function that takes one argument and returns another function expecting the second argument.
Characteristics of Binary Functions in Haskell
- Two Arguments: A binary function has a type signature of the form:
a -> b -> c
This means:
- It takes an argument of type
a
. - It takes another argument of type
b
. - It produces a result of type
c
.
2. Curried by Default: In Haskell, functions are curried by default. This means a binary function f :: a -> b -> c
is equivalent to a function that takes one argument (a
) and returns a function of type b -> c
.
3. Examples: Many common functions are binary, such as addition (+)
, subtraction (-)
, or concatenation (++)
.
Example of Binary Functions
Addition
The addition function (+)
is a binary function:
(+) :: Num a => a -> a -> a
-- Usage:
result = 3 + 5 -- Result: 8
Because it’s curried, you can partially apply it:
add3 :: Num a => a -> a
add3 = (+ 3)
result = add3 5 -- Result: 8
Custom Binary Function
You can define your own binary function:
multiply :: Int -> Int -> Int
multiply x y = x * y
-- Usage:
result = multiply 3 4 -- Result: 12
Higher-Order Binary Function
Binary functions are often passed to higher-order functions like foldl
or foldr
:
sumList :: [Int] -> Int
sumList = foldl (+) 0
result = sumList [1, 2, 3, 4] -- Result: 10
Here, (+)
is the binary function used to combine elements of the list.
Representing Binary Functions as Operators
In Haskell, many binary functions are written as infix operators for convenience:
(+)
for addition(++)
for list concatenation(==)
for equality comparison
You can also define your own binary infix operators:
(^|^) :: Int -> Int -> Int
x ^|^ y = x * x + y * y
result = 3 ^|^ 4 -- Result: 25
Summary
A binary function in Haskell is a function that takes two arguments, often written in the form a -> b -> c
. Because Haskell functions are curried, binary functions can be partially applied, making them powerful tools for composing and reusing functionality. Many built-in and custom operations in Haskell, from arithmetic to list processing, leverage binary functions.
Leave a Reply