Haskell is a programming language where variables do not exist. Therefore, it manipulates data through expressions called pure functions.
This shot focuses on the following two pure functions:
In Haskell, the maximum number in a list can be found using the recursive method.
In the code below, the maxNum
function is declared to indicate the types of parameters and the return value. The parameter Ord a
specifies any data type that is orderable, and [a]
indicates a list. The data type of the return value is the integer specified by a
.
If the list contains only one element, the function returns it without any comparison.
If the list contains more than one element, maxNum
calls itself recursively to first compare the initial two elements. After this, maxNum
compares the previous maximum number with the next element of the list. It keeps on doing this until it reaches the end of the list, where it returns the maximum number.
maxNum :: Ord a => [a] -> amaxNum [x] = xmaxNum (x:x':xs) = maxNum ((if x >= x' then x else x'):xs)main = print (maxNum [2, 6, 3, 70, 1])
The recursive method can also be used for finding the minimum number in a list.
The code below shows the minNum
function being called by itself, through recursion. The first line is the declaration of the function indicating the data type of the parameters and the return value. Ord b
specifies a type-class constraint, i.e., it can be of any data type that is orderable. The data type of parameter [b]
is list
, and the data type of the return value b
is an integer.
The function returns the same element if only one element is present in it.
If the list has more than one element, minNum
calls itself recursively to first compare the initial two elements. Then, minNum
compares the previous minimum number with the next entry of the list. It keeps on doing this until it reaches the end of the list, where it returns the minimum number.
minNum:: Ord b => [b]-> bminNum [x] = xminNum (x:x':xs) = minNum ((if x <= x' then x else x'):xs)main = print (minNum [1, -2, 3, -24, 64])