Skip to content

Instantly share code, notes, and snippets.

@nekketsuuu
Last active June 16, 2017 00:09
Show Gist options
  • Save nekketsuuu/018b378d75925a959909a340d803de27 to your computer and use it in GitHub Desktop.
Save nekketsuuu/018b378d75925a959909a340d803de27 to your computer and use it in GitHub Desktop.
:- dynamic memo/2.
:- retractall( (memo(_, _) ).
fib(N, 1) :-
N =< 2, !.
fib(N, Result) :-
memo(N, Result), !.
fib(N, Result) :-
N1 is N - 1,
fib(N1, Result1),
N2 is N - 2,
fib(N2, Result2),
Result is Result1 + Result2,
assert(memo(N, Result)).
% SWI-Prolog
:- use_module(library(clpfd)).
:- use_module(library(tabling)).
:- table fib/2.
fib(N, 1) :- N =< 2, !.
fib(N, Result) :-
N1 #= N - 1,
fib(N1, Result1),
N2 #= N - 2,
fib(N2, Result2),
Result #= Result1 + Result2.
% SWI-Prolog
% https://github.com/SWI-Prolog/swipl-devel/issues/226
:- use_module(library(clpfd)).
fib(N, 1) :- N #=< 2.
fib(N, Result) :-
N #> 2,
N1 #= N - 1,
N2 #= N - 2,
fib(N1, Result1),
fib(N2, Result2),
Result #= Result1 + Result2.
% SWI-Prolog
% https://www.metalevel.at/prolog/memoization
:- use_module(library(clpfd)).
:- dynamic memo_/1.
:- retractall( (memo_(_)) ).
memo(Goal) :-
( memo_(Goal)
-> true
; once(Goal),
assertz(memo_(Goal))
).
fib(N, 1) :- N #=< 2.
fib(N, Result) :-
N #> 2,
N1 #= N - 1,
N2 #= N - 2,
memo(fib(N1, Result1)),
memo(fib(N2, Result2)),
Result #= Result1 + Result2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment