简体   繁体   中英

Writing a recursive inRange function in haskell

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 ab []=[], however beyond this I'm completely lost. I've tried using guarded statements, however I'm still very lost.

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM