Kai D
Kai D

Reputation: 133

Writing a Between Numbers Function in Haskell

I'm currently working through The Craft of Functional Programming 2nd Edition and I have been presented with a task to write a between function which has stumped me.

The function takes three numbers as arguments and returns a boolean result i.e.

between :: Int -> Int -> Int -> Bool

It is defined so that between m n p is true if n is between n and p. For the sake of simplicity given between 2 2 2, the function would return true, also between 3 3 5 would return true.

Mathematically, x<=y and y<=z

The question also recommended that I could write a weakAscendingOrder function which checks that the number sequence doesn't go down at any point. I have written this function and my code is shown below:

weakAscendingOrder :: Int -> Int -> Int -> Bool
weakAscendingOrder x y z = (x <= y) && (y <= z)

How can I write a between function, either with or without using weakAscendingOrder, while preserving the function signatures since they have been provided by the book?

Upvotes: 1

Views: 3784

Answers (2)

yay nay
yay nay

Reputation: 1

There seems to be a good reason why the author of the book suggested the weakAscendingOrder as the help function for (or in) the 'between' function.

To my understanding, the 'between" function is not quite the same as the weakAscendingOrder function, this in the context of the original problem (middleNumber function) presented in the book.

Upvotes: 0

Chris
Chris

Reputation: 710

Comment two is exactly right. The weakAscendingOrder function behaves exactly like you want between to behave. Here are some additional flavors of implementation:

between x y z --using guards
  |x <= y = y <= z
  |otherwise = False

between x y z = if (x <= y) then (y <= z) else False --using if

between x y z = case (x <= y) of True  -> (y <= z) --using case syntax
                                 False -> False

however the (x<=y)&&(y<=z) is in my opinion very readable and does the job nicely.

Upvotes: 1

Related Questions