Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add exercise 'square-root' #245

Merged
merged 2 commits into from
Dec 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,17 @@
"stacks"
]
},
{
"slug": "square-root",
"name": "Square Root",
"uuid": "8f79d2ac-2407-4bba-91a8-6a47737e7f36",
"practices": [],
"prerequisites": [],
"difficulty": 4,
"topics": [
"math"
]
},
{
"slug": "allergies",
"name": "Allergies",
Expand Down Expand Up @@ -332,8 +343,8 @@
"prerequisites": [],
"difficulty": 1,
"topics": [
"lists",
"strings"
"lists",
"strings"
]
},
{
Expand All @@ -344,9 +355,9 @@
"prerequisites": [],
"difficulty": 1,
"topics": [
"lists",
"strings",
"text_formatting"
"lists",
"strings",
"text_formatting"
]
},
{
Expand Down Expand Up @@ -398,7 +409,7 @@
]
},
"concepts": [],
"key_features": [
"key_features": [
{
"title": "Algebraic data types",
"content": "Easy to define and easy to use, with robust pattern matching and pattern-exhaustiveness.",
Expand Down
13 changes: 13 additions & 0 deletions exercises/practice/square-root/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Instructions

Given a natural radicand, return its square root.

Note that the term "radicand" refers to the number for which the root is to be determined.
That is, it is the number under the root symbol.

Check out the Wikipedia pages on [square root][square-root] and [methods of computing square roots][computing-square-roots].

Recall also that natural numbers are positive real whole numbers (i.e. 1, 2, 3 and up).

[square-root]: https://en.wikipedia.org/wiki/Square_root
[computing-square-roots]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
19 changes: 19 additions & 0 deletions exercises/practice/square-root/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"keiravillekode"
],
"files": {
"solution": [
"square-root.sml"
],
"test": [
"test.sml"
],
"example": [
".meta/example.sml"
]
},
"blurb": "Given a natural radicand, return its square root.",
"source": "wolf99",
"source_url": "https://github.com/exercism/problem-specifications/pull/1582"
}
19 changes: 19 additions & 0 deletions exercises/practice/square-root/.meta/example.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
(* We use Heron's method, with rounding to the nearest natural number.
* https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Heron's_method
* estimate = (guess + randicand / guess) / 2
* = (guess * guess + randicand) / (2 * guess)
* To achieve rounding when using integer division,
* we must increase the numerator by half the denominator.
*)
fun squareRoot (radicand: int): int =
let
fun recurse guess =
let
val estimate = (guess * (guess + 1) + radicand) div (2 * guess)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you provide a brief description or reference for the methodology which is used to compute the square root (as a docstring)? This looks a bit like Heron's method, but possibly slightly adapted to the integer world?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment added. We implement Heron's method using integer arithmetic, rounding the estimate to the nearest natural number.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK sounds reasonable. I didn't rigorously check it though, the tests pass and I assume that you made sure some kind of correctness in general?

If yes I will merge it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have tested radicand values 1 .. 10000

My V implementation also works for 0, but that isn't important as the instructions exclude 0.

in
if estimate = guess then estimate
else recurse estimate
end
in
recurse 1
end
28 changes: 28 additions & 0 deletions exercises/practice/square-root/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[9b748478-7b0a-490c-b87a-609dacf631fd]
description = "root of 1"

[7d3aa9ba-9ac6-4e93-a18b-2e8b477139bb]
description = "root of 4"

[6624aabf-3659-4ae0-a1c8-25ae7f33c6ef]
description = "root of 25"

[93beac69-265e-4429-abb1-94506b431f81]
description = "root of 81"

[fbddfeda-8c4f-4bc4-87ca-6991af35360e]
description = "root of 196"

[c03d0532-8368-4734-a8e0-f96a9eb7fc1d]
description = "root of 65025"
2 changes: 2 additions & 0 deletions exercises/practice/square-root/square-root.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fun squareRoot (radicand: int): int =
raise Fail "'squareRoot' is not implemented"
30 changes: 30 additions & 0 deletions exercises/practice/square-root/test.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
(* version 1.0.0 *)

use "testlib.sml";
use "square-root.sml";

infixr |>
fun x |> f = f x

val testsuite =
describe "square-root" [
test "root of 1"
(fn _ => squareRoot 1 |> Expect.equalTo 1),

test "root of 4"
(fn _ => squareRoot 4 |> Expect.equalTo 2),

test "root of 25"
(fn _ => squareRoot 25 |> Expect.equalTo 5),

test "root of 81"
(fn _ => squareRoot 81 |> Expect.equalTo 9),

test "root of 196"
(fn _ => squareRoot 196 |> Expect.equalTo 14),

test "root of 65025"
(fn _ => squareRoot 65025 |> Expect.equalTo 255)
]

val _ = Test.run testsuite
160 changes: 160 additions & 0 deletions exercises/practice/square-root/testlib.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
structure Expect =
struct
datatype expectation = Pass | Fail of string * string

local
fun failEq b a =
Fail ("Expected: " ^ b, "Got: " ^ a)

fun failExn b a =
Fail ("Expected: " ^ b, "Raised: " ^ a)

fun exnName (e: exn): string = General.exnName e
in
fun truthy a =
if a
then Pass
else failEq "true" "false"

fun falsy a =
if a
then failEq "false" "true"
else Pass

fun equalTo b a =
if a = b
then Pass
else failEq (PolyML.makestring b) (PolyML.makestring a)

fun nearTo delta b a =
if Real.abs (a - b) <= delta * Real.abs a orelse
Real.abs (a - b) <= delta * Real.abs b
then Pass
else failEq (Real.toString b ^ " +/- " ^ Real.toString delta) (Real.toString a)

fun anyError f =
(
f ();
failExn "an exception" "Nothing"
) handle _ => Pass

fun error e f =
(
f ();
failExn (exnName e) "Nothing"
) handle e' => if exnMessage e' = exnMessage e
then Pass
else failExn (exnMessage e) (exnMessage e')
end
end

structure TermColor =
struct
datatype color = Red | Green | Yellow | Normal

fun f Red = "\027[31m"
| f Green = "\027[32m"
| f Yellow = "\027[33m"
| f Normal = "\027[0m"

fun colorize color s = (f color) ^ s ^ (f Normal)

val redit = colorize Red

val greenit = colorize Green

val yellowit = colorize Yellow
end

structure Test =
struct
datatype testnode = TestGroup of string * testnode list
| Test of string * (unit -> Expect.expectation)

local
datatype evaluation = Success of string
| Failure of string * string * string
| Error of string * string

fun indent n s = (implode (List.tabulate (n, fn _ => #" "))) ^ s

fun fmt indentlvl ev =
let
val check = TermColor.greenit "\226\156\148 " (* ✔ *)
val cross = TermColor.redit "\226\156\150 " (* ✖ *)
val indentlvl = indentlvl * 2
in
case ev of
Success descr => indent indentlvl (check ^ descr)
| Failure (descr, exp, got) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) exp,
indent (indentlvl + 2) got]
| Error (descr, reason) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) (TermColor.redit reason)]
end

fun eval (TestGroup _) = raise Fail "Only a 'Test' can be evaluated"
| eval (Test (descr, thunk)) =
(
case thunk () of
Expect.Pass => ((1, 0, 0), Success descr)
| Expect.Fail (s, s') => ((0, 1, 0), Failure (descr, s, s'))
)
handle e => ((0, 0, 1), Error (descr, "Unexpected error: " ^ exnMessage e))

fun flatten depth testnode =
let
fun sum (x, y, z) (a, b, c) = (x + a, y + b, z + c)

fun aux (t, (counter, acc)) =
let
val (counter', texts) = flatten (depth + 1) t
in
(sum counter' counter, texts :: acc)
end
in
case testnode of
TestGroup (descr, ts) =>
let
val (counter, texts) = foldr aux ((0, 0, 0), []) ts
in
(counter, (indent (depth * 2) descr) :: List.concat texts)
end
| Test _ =>
let
val (counter, evaluation) = eval testnode
in
(counter, [fmt depth evaluation])
end
end

fun println s = print (s ^ "\n")
in
fun run suite =
let
val ((succeeded, failed, errored), texts) = flatten 0 suite

val summary = String.concatWith ", " [
TermColor.greenit ((Int.toString succeeded) ^ " passed"),
TermColor.redit ((Int.toString failed) ^ " failed"),
TermColor.redit ((Int.toString errored) ^ " errored"),
(Int.toString (succeeded + failed + errored)) ^ " total"
]

val status = if failed = 0 andalso errored = 0
then OS.Process.success
else OS.Process.failure

in
List.app println texts;
println "";
println ("Tests: " ^ summary);
OS.Process.exit status
end
end
end

fun describe description tests = Test.TestGroup (description, tests)
fun test description thunk = Test.Test (description, thunk)