Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modular Arithmetic in Haskell

How would I go about making a function so that x has a range of values from x=0 to x=19 and if the x value exceeds 19 or is below zero how can I get it to wrap around

From: x=20, x=21, x=22 and x=(-1), x=(-2), x=(-3)

To: x=0, x=1, x=2 and x=19, x=18, x=17 respectively?

I've heard of modular arithmetic which is apparently the way I should deal with it.

like image 303
maclunian Avatar asked Dec 21 '22 13:12

maclunian


1 Answers

Usually you would use the built-in functions mod and rem, but I assume they are off-limits for homework. So you can write your own function, e.g.

mod20 x | x < 0 = ...
        | x > 19 = ...
        | otherwise = x

There are different things you can try to fill in the ...s. One of the easiest is repeated addition or subtraction, but I don't want to spoil all the fun.

Once you have this function, you can "rescale" the values after every "normal" arithmetic operation, e.g. mod20 (12 + 17).

like image 101
Landei Avatar answered Jan 10 '23 20:01

Landei