-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New module Loop with loop : (a -> Either a b) -> a -> b
- Loading branch information
1 parent
df308eb
commit e937de0
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
|
||
open import Haskell.Prelude | ||
|
||
module Haskell.Extra.Loop where | ||
|
||
IsJust : Maybe a → Set | ||
IsJust Nothing = ⊥ | ||
IsJust (Just _) = ⊤ | ||
|
||
fromJust : (x : Maybe a) → @0 {IsJust x} → a | ||
fromJust (Just x) = x | ||
fromJust Nothing = error "fromJust called on Nothing" | ||
|
||
data Fuel (f : a → Either a b) : (x : Either a b) → Set where | ||
done : ∀ {y} → Fuel f (Right y) | ||
more : ∀ {x} → Fuel f (f x) → Fuel f (Left x) | ||
|
||
tryFuel : (f : a → Either a b) (x : Either a b) (n : Nat) → Maybe (Fuel f x) | ||
tryFuel f x zero = Nothing | ||
tryFuel f (Left x) (suc n) = more <$> tryFuel f (f x) n | ||
tryFuel f (Right y) (suc n) = Just done | ||
|
||
getFuel : (f : a → Either a b) (x : Either a b) (n : Nat) | ||
→ {IsJust (tryFuel f x n)} → Fuel f x | ||
getFuel f x n {p} = fromJust (tryFuel f x n) {p} | ||
|
||
module _ {a b : Set} where | ||
loop : (f : a → Either a b) (x : a) → @0 Fuel f (Left x) → b | ||
loop f x (more n) = go (f x) n | ||
where | ||
go : (x : Either a b) → @0 Fuel f x → b | ||
go (Left x) (more n) = go (f x) n | ||
go (Right y) done = y | ||
{-# COMPILE AGDA2HS loop #-} |