Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing remainder without using modulus operator F#

Tags:

f#

c#-to-f#

I have implemented my code which is basically to compute remainder in two numbers without using modulus operator however, I am stuck in a situation which is just hectic. I know the logic however I am newbie in f# and dont know how to implement it.

let rec modulus a b =
if b = 0 Console.WriteLine("Sorry Wrong Divisor")
let bool neg = a < 0
a = abs a
b = abs b
modulus(val-divisor,divisor)

All I know is I am getting a pretty basic mistake here, Any help,

like image 403
Umair Sajid Avatar asked May 05 '26 01:05

Umair Sajid


1 Answers

The first step towards getting this to work is to fix your indentation and turn your sketch into valid F# code that actually compiles and runs - that should help you get to the next step, which is to fix the logic of the implementation.

A minimal code that is similar to yours and actually runs looks like this:

let rec modulus value divisor : int =
  printfn "value=%d, divisor=%d" value divisor
  if divisor = 0 then Console.WriteLine("Sorry Wrong Divisor")
  let neg = value < 0
  let value = abs value
  let divisor = abs divisor
  modulus (value-divisor) divisor

modulus 10 5
  • I fixed the indentation - F# is indentation sensitive, so this matters.
  • I replaced your a = abs a with let - the let keyword defines a new variable, hiding the existing one (as you cannot mutate existing variables - they are immutable in F#)
  • I renamed your variables to consistently use divisor and value names
  • I added printfn so that you can see how the function runs (it will get into an infinite loop, because it currently never checks for the termination condition!)
  • I had to add type annotation : int to say that the result will be int - as your function never returns, this is required (but you can remove it once you fix this)
like image 64
Tomas Petricek Avatar answered May 06 '26 21:05

Tomas Petricek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!