Skip to content

Commit aa4cf87

Browse files
authored
optimize Natural/fold in the strict case (#2585)
1 parent 3b47381 commit aa4cf87

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

dhall/src/Dhall/Eval.hs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ instance Semigroup (VChunks a) where
122122
VChunks xys z <> VChunks [] z' = VChunks xys (z <> z')
123123
VChunks xys z <> VChunks ((x', y'):xys') z' = VChunks (xys ++ (z <> x', y'):xys') z'
124124

125-
instance Monoid (VChunks b) where
125+
instance Monoid (VChunks a) where
126126
mempty = VChunks [] mempty
127127

128128
{-| Some information is lost when `eval` converts a `Lam` or a built-in function
@@ -527,9 +527,13 @@ eval !env t0 =
527527
-- following issue:
528528
--
529529
-- https://github.com/ghcjs/ghcjs/issues/782
530-
let go !acc 0 = acc
531-
go acc m = go (vApp succ acc) (m - 1)
532-
in go zero (fromIntegral n' :: Integer)
530+
go zero (fromIntegral n' :: Integer) where
531+
go !acc 0 = acc
532+
go (VNaturalLit x) m =
533+
case vApp succ (VNaturalLit x) of
534+
VNaturalLit y | x == y -> VNaturalLit x
535+
notNaturalLit -> go notNaturalLit (m - 1)
536+
go acc m = go (vApp succ acc) (m - 1)
533537
_ -> inert
534538
NaturalBuild ->
535539
VPrim $ \case

dhall/src/Dhall/Normalize.hs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,16 @@ normalizeWithM ctx e0 = loop (Syntax.denote e0)
211211
strict = strictLoop (fromIntegral n0 :: Integer)
212212
lazy = loop ( lazyLoop (fromIntegral n0 :: Integer))
213213

214-
strictLoop 0 = loop zero
215-
strictLoop !n = App succ' <$> strictLoop (n - 1) >>= loop
214+
strictLoop !n = do
215+
z <- loop zero
216+
strictLoopShortcut n z
217+
218+
strictLoopShortcut 0 !previous = pure previous
219+
strictLoopShortcut !n !previous = do
220+
current <- loop (App succ' previous)
221+
if judgmentallyEqual previous current
222+
then pure previous
223+
else strictLoopShortcut (n - 1) current
216224

217225
lazyLoop 0 = zero
218226
lazyLoop !n = App succ' (lazyLoop (n - 1))

0 commit comments

Comments
 (0)