Skip to content

Instantly share code, notes, and snippets.

@ninjarobot
Created January 13, 2020 21:00
Show Gist options
  • Save ninjarobot/1776346c6e9bfd989e580809980f6b31 to your computer and use it in GitHub Desktop.
Save ninjarobot/1776346c6e9bfd989e580809980f6b31 to your computer and use it in GitHub Desktop.
Division by subtraction example in F#
type DivisionProblem =
{
Dividend : int
Divisor : int
}
type DivisionSolution =
{
Quotient : int
Remainder : int
Divisor : int
}
member solution.AsString =
if solution.Remainder = 0 then string solution.Quotient
else String.Format ("{0}-{1}/{2}", solution.Quotient, solution.Remainder, solution.Divisor)
let divide (problem:DivisionProblem) =
let rec divisionBySubtraction (solutionSoFar:DivisionSolution) =
if solutionSoFar.Remainder > problem.Divisor then
divisionBySubtraction
{ solutionSoFar with
Quotient = solutionSoFar.Quotient + 1
Remainder = solutionSoFar.Remainder - problem.Divisor }
elif solutionSoFar.Remainder = problem.Divisor then
{ solutionSoFar with
Quotient = solutionSoFar.Quotient + 1
Remainder = 0 }
else
solutionSoFar
divisionBySubtraction { Quotient = 0; Remainder = problem.Dividend; Divisor = problem.Divisor }
[<Fact>]
let tryDivision () =
let five = divide { Dividend = 55; Divisor = 11 }
let sixAndSevenEighths = divide { Dividend = 55; Divisor = 8 }
let one = divide { Dividend=10; Divisor=10 }
Assert.Equal(5, five.Quotient)
Assert.Equal(0, five.Remainder)
Assert.Equal(6, sixAndSevenEighths.Quotient)
Assert.Equal(7, sixAndSevenEighths.Remainder)
Assert.Equal(8, sixAndSevenEighths.Divisor)
Assert.Equal(1, one.Quotient)
Assert.Equal(0, one.Remainder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment