2

I've been given an exercise to write an inRange function via recursion ie: give two numbers (signifying the range) with a list and it should return a new list with all the numbers between those two, including the two supplied range numbers.

obviously one of the base cases should be if the list is empty ie inRange a b []=[], however beyond this I'm completely lost. I've tried using guarded statements, however I'm still very lost.

1
  • 2
    What have you done so far ? Commented Nov 27, 2015 at 15:48

2 Answers 2

3

As always recursions consists out of two parts:

  • one or more base cases, here for instance the empty list:

    inRange _ _ [] = []
    
  • on or more recursive cases (or inductive cases). Evidently, this is the case when the list is not empty.

Now for the latter, there are two options: either the first number of the list is in the range, or it is not. In case it is, we enumerate it, in case it is not, we do not enumerate:

inRange a b (x:xs) | a <= x && x <= b = x : tl
                   | otherwise = tl
                   where tl = inRange a b xs

So the full implementation reads:

inRange a b (x:xs) | a <= x && x <= b = x : tl
                   | otherwise = tl
                   where tl = inRange a b xs
inRange _ _ _ = []

Here we have written the base case at the bottom: the advantage is that - at least conceptually - Haskell evaluates from top to bottom, and evidently it is less likely the list will be empty.

Furthermore we can use don't cares (_) on all parameters such that we are certain all possible cases are covered and thus that the function is at least total (meaning for any kind of input, you will always receive output, although this evidently does not prove correctness).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solution is perfect! Thanks for making everything much clearer.
0

How about this?

inRange :: Int -> Int -> [Int]
inRange x y | x == y = [x]
            | x < y = x : inRange (x + 1) y

You don't actually have to pass the list as a parameter for this

4 Comments

I think you read the problem specs wrong: you are given a list and needs to perform some kind of filtering operation on it if I understand it correctly.
sorry - just reread your post and you want to pass in a list, I'll leave the answer here for reference though
was not my post, but anyway ;).
Haha - I think we commented at basically the same time ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.