Monday 6 June 2016

Haskell: Return numbers from x to y

Write a function, that takes two numbers as arguments and return numbers from x to y.


ListUtil.hs
printInfo :: Integer -> Integer -> [Integer]
printInfo x y
    | (x == y) = []
    | (x > y) = printInfo' x y (-1)
    | otherwise = printInfo' x y 1

printInfo' :: Integer -> Integer -> Integer -> [Integer]
printInfo' x y increment
    | (x == y) = []
    | otherwise = x : (printInfo' (x+increment) y increment)

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> printInfo 10 20
[10,11,12,13,14,15,16,17,18,19]
*Main> 
*Main> printInfo 10 (-20)
[10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19]
*Main> 
*Main> printInfo 10 10
[]
*Main> printInfo 10 9
[10]
*Main> printInfo 9 10
[9]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment