[m-users.] Trying to understand a predicate for calculating Fibonacci numbers

zeldangit zeldangit at gmail.com
Thu Nov 9 10:15:30 AEDT 2017


So I am trying to understand the following code. How is X = A + B searched
for? So A + B has to add up to X, which is passed to the function, but
there is no explanation of how Mercury discovers these variables that add
up to X.

Also, should I read a Prolog book to have a better grasp of Mercury?

:- module fib.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det
.
:- implementation.
:- import_module int.
:- pred fib(int::in, int::out) is det.

fib(N, X) :-
( if   N =< 2
  then X = 1
  else fib(N - 1, A), fib(N - 2, B), X = A + B
).
main(!IO) :-
   fib(17, X),
   io.write_string("fib(17, ", !IO),
   io.write_int(X, !IO),
   io.write_string(")\n", !IO).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mercurylang.org/archives/users/attachments/20171108/b69b8e56/attachment-0001.html>


More information about the users mailing list