I do want to compare an integer (rstart) with an integer (number) in the following way (C code):
#include <stdio.h>
#include <stdlib.h>
int main (void){
int rstart = 15, rend = 25, number = 629;
while (rstart <= rend){
rstart ;
if (number % rstart == 0){
return number % rstart;
}
}
return number % rstart;
}
Now I do know how to write something like this in c or python but I do have no clue how to do it in Haskell.
I did start out with the following:
dividesRange :: Integer -> Integer -> Integer -> Bool
dividesRange number rstart rend =
I do not know how I would implement the while loop from C in Haskell. I know I could use all if statements but that is inefficient in my opinion. Is there an easy way to write this in Haskell?
CodePudding user response:
dividesRange :: Integer -> Integer -> Integer -> Bool
dividesRange number rstart rend = go rstart where
go x
| x > rend = False
| otherwise = number `rem` x == 0 || go (x 1)
How it works:
- We use a helper function
go
. - The base case is when
x
(rstart), is greater thanrend
. In that case we return False. - Otherwise we check if the remainder of
number
divided byx
is zero. If so, we return True and don't recurse further. - Otherwise we increase
x
and callgo
again.
Using any
we can rewrite the above as follows:
dividesRange2 :: Integer -> Integer -> Integer -> Bool
dividesRange2 number rstart rend = any (\x -> number `rem` x == 0) [rstart..rend]