maclunian
maclunian

Reputation: 8023

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.

Upvotes: 4

Views: 2905

Answers (3)

aleator
aleator

Reputation: 4486

Try using the mod function:

(-5) `mod` 20 ==> 15
5 `mod` 20 ==> 5
20 `mod` 20 ==> 0
25 `mod` 20 ==> 5

See also wikipedia on the topic.

Upvotes: 4

Landei
Landei

Reputation: 54574

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

Upvotes: 7

augustss
augustss

Reputation: 23014

Use

x `mod` 20

(This is a filler to make the answer 30 characters.)

Upvotes: 1

Related Questions