Skip to content

Commit

Permalink
feat: added absolute value and square root
Browse files Browse the repository at this point in the history
  • Loading branch information
korbexmachina committed Mar 15, 2024
1 parent aad26c4 commit 72e53d5
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/gcalc.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import gleam/io

pub fn main() {
io.println("Hello from calc!")
io.println("Hello from gcalc!")
}
35 changes: 35 additions & 0 deletions src/gcalc/alg.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//// A set of algebraic operations for the for Gleam programs

import gleam/float

/// Return the exponentiation of the two arguments
pub fn pow(base: Int, power: Int, accumulator: Int) -> Int {
case power {
Expand All @@ -15,3 +17,36 @@ pub fn factorial(n: Int) -> Int {
_ -> n * factorial(n - 1)
}
}

/// Return the square root of the argument
pub fn sqrt(n: Float) -> Float {
case n {
0.0 -> 0.0
_ -> {
let x0 = n /. 2.0
let x1 = { x0 +. n /. x0 } /. 2.0
sqrt_iter(x0, x1, n)
|> float.floor()
}
}
}

/// Helper function for the square root function
fn sqrt_iter(x0: Float, x1: Float, n: Float) -> Float {
case abs(x1 -. x0) <. 0.0001 {
True -> x1
False -> {
let x0 = x1
let x1 = { x0 +. n /. x0 } /. 2.0
sqrt_iter(x0, x1, n)
}
}
}

/// Return the absolute value of the argument
pub fn abs(n: Float) -> Float {
case n <. 0.0 {
True -> 0.0 -. n
False -> n
}
}
36 changes: 36 additions & 0 deletions test/gcalc_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,39 @@ pub fn factorial_5_test() {
alg.factorial(5)
|> should.equal(120)
}

/// Test that sqrt(4) = 2
pub fn sqrt_4_test() {
alg.sqrt(4.0)
|> should.equal(2.0)
}

/// Test that sqrt(9) = 3
pub fn sqrt_9_test() {
alg.sqrt(9.0)
|> should.equal(3.0)
}

/// Test that sqrt(16) = 4
pub fn sqrt_16_test() {
alg.sqrt(16.0)
|> should.equal(4.0)
}

/// Test that |3| = 3
pub fn abs_3_test() {
alg.abs(3.0)
|> should.equal(3.0)
}

/// Test that |-3| = 3
pub fn abs_neg3_test() {
alg.abs(-3.0)
|> should.equal(3.0)
}

/// Test that |0| = 0
pub fn abs_0_test() {
alg.abs(0.0)
|> should.equal(0.0)
}

0 comments on commit 72e53d5

Please sign in to comment.