mert
mert

Reputation: 153

How i can list all the numbers between the two given numbers without bulit-in functions

I need to write a function that makes the same job as [a..b] by using the : operator and guards.

is it possible to do it? where should I begin?

 list a b 
            | a < b = print[a..b]
            | otherwise = print[a,a-1..b]

Upvotes: 1

Views: 115

Answers (2)

mert
mert

Reputation: 153

Is it better to compare with the parent function or within the same function? @Will Ness

list a b| a < b = greaterB a b    
list a b| a >= b = greaterA a b


greaterB a b 
           | a > b = []             
           | a <= b = a:greaterB(a+1) b

greaterA a b 
           | a >= b = a:greaterA(a-1) b               
           | a < b = []

Upvotes: 1

Will Ness
Will Ness

Reputation: 71070

You can try deriving it from the laws it must follow, i.e.

list a b | a > b = []
list a b | a <= b = [a..b]
                  = a : [(a+1)..b]

But then we can read the last equation right to left to get

[(a+1)..b] = list (a+1) b

and substituting it back into the last law gives us the definition that we needed.

update: so looks like what you really wanted is to count up or down depending on the relation between a and b. This just needs some tweaking:

list a b | a == b = [a]
list a b | a < b  = [a..b]
                  = a : [(a+1)..b]
                  = a : list (a+1) b
list a b | a > b  = [a,a-1..b]
                  = a : [a-1,a-2..b]
                  = a : list (a-1) b

This will perform some redundant checks while counting. These can be avoided by defining two specialized internal functions for the counting up or down, and using those after the initial checks.

Upvotes: 1

Related Questions