Search code examples
haskellfunctional-programmingprimitive

haskell modulus primitive recursion


I'm trying to create a modulus function within haskell using primtive recursive functions. I know it's possible (because it's on the list of example functions on wikipedia)

And I know how i'd logically do it too.. But I just can't implement it!

IE, the logic is (not primtive recursion or haskell)

function mod(a, b){
  while(a > b)
    a -= b
  return a;
}

Which I can define using recursion (again not haskel)

function mod(a, b){
  if(a < b) return a;
  return mod(a - b, b);
} 

But I just can't seem to implement it using primitive recursive functions. I bit which I can't do is the logic of a < b

I think to really solve my problem I need some sort of defined logic such as (again not haskel)

reduce(a, b)
    = a >= b -> a-b 
    otherwise x

If anyone could help me with any part of this i'd really appreciate it, thanks

Edit:: I thought of potentially defining a modulus function making use of dividing, ie mod(a, b) = a - (a/b) * b, but since my primitive recursive function for divide relies on modulo I can't do it haha


Solution

  • The solution to this is

    mod(0, y)
            = zero(y)
    mod(x, 0)
            = zero(x)
    mod(x + 1, y)
            = mult3(succ(mod(x, y)), sign(y), notsign(eq(mod(x, y), diff(y, 1))))