// Souffle - A Datalog Compiler
// Copyright (c) 2016, The Souffle Developers. All rights reserved
// Licensed under the Universal Permissive License v 1.0 as shown at:
// - https://opensource.org/licenses/UPL
// - <souffle root>/licenses/SOUFFLE-UPL.txt

// Generate the Catalan numbers

// Generated catalan numbers will never exceed lim(n).
.decl lim(n : number)
.input lim()

.decl naturals(n : number)
naturals(0).
naturals(n+1) :- naturals(n), n < s, lim(s).

// Binomial Coefficients
.decl choose(n : number, k : number, v : number)
choose(n, n, 1) :- naturals(n).
choose(n, (n - k), v) :- choose(n, k, v).
choose(n+1, k+1, v1 + v2) :- choose(n, k, v1), choose(n, k+1, v2).

.decl catalan(n : number, v: number)
.output catalan()
catalan(n, v) :- choose(2*n, n, c), naturals(v), v=c/(n+1).


