Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

haskell
communitycreator
maxnum
minnum

How to find the maximum and minimum numbers in a Haskell list

Mahnoor Zaheer

Overview

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:

  • Finding the maximum number in a list
  • Finding the minimum number in a list

Finding the maximum number

In Haskell, the maximum number in a list can be found using the recursive method.

Explanation

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.

Case 1:

If the list contains only one element, the function returns it without any comparison.

Case 2:

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] -> a
maxNum [x] = x
maxNum (x:x':xs) = maxNum ((if x >= x' then x else x'):xs)

main = print (maxNum [2, 6, 3, 70, 1])
The code for finding the maximum number in a list

Finding the minimum number

The recursive method can also be used for finding the minimum number in a list.

Explanation

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.

Case 1:

The function returns the same element if only one element is present in it.

Case 2:

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]-> b
minNum [x] = x
minNum (x:x':xs) = minNum ((if x <= x' then x else x'):xs)

main = print (minNum [1, -2, 3, -24, 64])
The code for finding the minimum number in a list

RELATED TAGS

haskell
communitycreator
maxnum
minnum
RELATED COURSES

View all Courses

Keep Exploring