Skip to content
Draft
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ New modules
* `Data.Bool.ListAction.Properties` for properties of conjunction and
disjunction of lists.

* `Data.Nat.Sqrt.Base` defines the square root of `n` as the greatest
natural number whose square is less than or equal to `n`, using a
primtive recursive definition originally due to Goodstein (1957).

* A new type of lists that grow on the right.
This is typically useful to model contexts of typing rules
or type accumulators that need to be reversed in the base case.
Expand Down
36 changes: 36 additions & 0 deletions src/Data/Nat/Sqrt/Base.agda
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
------------------------------------------------------------------------
-- The Agda standard library
--
-- Natural number square root
--
-- Goodstein's (1957) primitive recursive definition, taken from
-- Troelstra and van Dalen, Constructivity in Mathematics, Vol. I
------------------------------------------------------------------------

{-# OPTIONS --without-K --safe #-}

module Data.Nat.Sqrt.Base where

open import Data.Bool.Base using (if_then_else_)
open import Data.Nat.Base using (ℕ; zero; suc; 2+; _+_; _∸_; _<ᵇ_)

sqrt : ℕ → ℕ
sqrt zero = zero
sqrt (suc n) = if (0 <ᵇ d) then √n else suc √n
module Sqrt where
-- helper functions to compute d
2*_ : ℕ → ℕ

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Maybe 2*_ should be a function in Data.Nat.Base that is exported?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Note that the generated code will be slower than simply using 2 * m.

2* zero = zero
2* suc m = 2+ (2* m)
_^2+2*_∸_ : ℕ → ℕ → ℕ → ℕ
zero ^2+2* n ∸ o = (2* n) ∸ o
(suc m) ^2+2* n ∸ o = m ^2+2* (suc (m + n)) ∸ (suc o)
-- then recur on n
√n = sqrt n
d = √n ^2+2* √n ∸ n

private
open import Agda.Builtin.Equality using (_≡_; refl)

test : sqrt 16 ≡ 4
test = refl
Loading