Skip to content

Commit

Permalink
add some tests and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
imalsogreg committed Jun 30, 2023
1 parent 58dca3b commit d2043e1
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Pact/Repl/Lib.hs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,10 @@ replDefs = ("Repl",

[]
("WIP")
,defZRNative "env-clear-memotable" envClearMemotable
(funType tTyString [])
["(env-clear-memotable)"]
"Reset the memoization table."
])
where
json = mkTyVar "a" [tTyInteger,tTyString,tTyTime,tTyDecimal,tTyBool,
Expand Down Expand Up @@ -916,4 +920,10 @@ envMemoize _i [TApp (App memoFun memoArgs _) _ ] = do
let table1 = unguardedInsert (entry, result') table0
evalMemoTable .= table1
return $ deepseq table1 $ tStr "Ok"
envMemoize _i _ = error "Wrong args"
envMemoize i as = argsError' i as

envClearMemotable :: RNativeFun LibState
envClearMemotable _i [] = do
evalMemoTable .= mempty
return $ tStr "Ok"
envClearMemotable i as = argsError i as
6 changes: 6 additions & 0 deletions src/Pact/Types/Memoize.hs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ data MemoTable = MemoTable {
instance NFData MemoTable
instance Default MemoTable where def = MemoTable mempty

instance Semigroup MemoTable where
MemoTable a <> MemoTable b = MemoTable (a <> b)

instance Monoid MemoTable where
mempty = MemoTable mempty

-- Insert a pair of function application and result into the memotable.
-- Insertion is guarded by a `Witness` - a means of asserting that
-- the pair is valid. The `Witness` is evaluated in some monad,
Expand Down
32 changes: 32 additions & 0 deletions tests/pact/memoize.repl
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
(env-gasmodel "table")
(env-gaslimit 1000000)

; Define an expensive function, which we will use to test memoization.
(module m g
(defcap g () true)
(defun go(n:integer) "Do an expensive computation"
(let ((xs (enumerate 1 n))
(fn (lambda (a b) (+ a b))))
(fold (fn) 0 xs)
)))

; We will test memoization by checking that gas usage is lower
; for a memo table hit than for a miss.
(env-gas 0)
(m.go 10)
(expect "Executing unmemoized function costs gas" 36 (env-gas))

(env-memoize (m.go 10))
(env-gas 0)
(m.go 10)
(expect "Executing memoized function is cheap" 0 (env-gas))


(env-gas 0)
(shift 10 (shift 1 1))
(expect "Executing unmemoized native costs gas" 3 (env-gas))

(env-memoize (shift 10 (shift 1 1)))
(env-gas 0)
(shift 10 2)
(expect "Executing memoized native is cheap" 0 (env-gas))

0 comments on commit d2043e1

Please sign in to comment.