on master help sign in
Merge pull request #1600 from markuspf/cast-fix-master

Make Cast instance for Nat to Int tail recursive

commit99277357fa404eef29bab76c7544f0d4563a34ee authorEdwin Brady <edwin.brady@gmail.com> dateTue 7 Oct 2014, 17:46 (12 years ago) parent4abeeeb8c8ad97
1 file changed+9−3
libs/prelude/Prelude/Nat.idr+9−3
libs/prelude/Prelude/Nat.idr+9−3
@@ -156,6 +156,14 @@ maximum Z m = m
156156maximum (S n) Z = S n
157157maximum (S n) (S m) = S (maximum n m)
158158
159+||| Tail recursive cast Nat to Int
160+||| Note that this can overflow
161+toIntNat : Nat -> Int
162+toIntNat n = toIntNat' n 0 where
163+ toIntNat' : Nat -> Int -> Int
164+ toIntNat' Z x = x
165+ toIntNat' (S n) x = toIntNat' n (x + 1)
166+
159167--------------------------------------------------------------------------------
160168-- Type class instances
161169--------------------------------------------------------------------------------
@@ -245,9 +253,7 @@ instance Cast Int Nat where
245253 cast i = fromInteger (cast i)
246254
247255instance Cast Nat Int where
248− cast Z = 0
249− cast (S n) = 1 + cast {to=Int} n
250−
256+ cast = toIntNat
251257
252258--------------------------------------------------------------------------------
253259-- Auxilliary notions