Syed Ahamed
Syed Ahamed

Reputation: 83

How can I find the smallest of 3 integers in Haskell?

As a beginner in Haskell I am trying to write a code to find the smallest number out of 3 integers. This is what I have so far. Can anyone push me in the right direction?

smallest :: Int -> Int -> Int -> Int
smallest a b c = min a b c

Upvotes: 3

Views: 4045

Answers (3)

Marat Gareev
Marat Gareev

Reputation: 427

Pointfree style:

smallest :: Int -> Int -> Int -> Int
smallest = (min .) . min

Upvotes: 0

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39400

@Zheka's code works fine for three numbers, and if you ever needed more, it's enough to notice that min a (min b c) looks just like a fold:

smallest a b c = foldl1 min [a, b, c]

Upvotes: 5

ZhekaKozlov
ZhekaKozlov

Reputation: 39654

min function accepts two arguments, that's why your code doesn't compile. However, your can call min twice:

smallest :: Int -> Int -> Int -> Int
smallest a b c = min a (min b c)

If you are unsatisfied with calling it twice and want a more concise solution, you can use minimum function. It accepts a list and returns its minimum value:

smallest :: Int -> Int -> Int -> Int
smallest a b c = minimum [a, b, c]

Upvotes: 10

Related Questions