# Does SWI-Prolog have N+K-trees?

**URL:** <https://swi-prolog.discourse.group/t/does-swi-prolog-have-n-k-trees/1310>\
**Category:** Data Structure\
**Created:** [September 24, 2019, 2:14pm UTC](https://swi-prolog.discourse.group/t/does-swi-prolog-have-n-k-trees/1310 "2019-09-24T14:14:34Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![jan](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/jan/32/4_2.png) [@jan](https://swi-prolog.discourse.group/u/jan)\
**Post date:** [September 25, 2019, 3:41pm UTC](https://swi-prolog.discourse.group/t/does-swi-prolog-have-n-k-trees/1310/5 "2019-09-25T15:41:19Z")

</div>

It is always a bit of work to get the math correct. After a little playing, I get at:

```prolog
:- debug(dyn).

dyn_new(Max, Dyn) :-
    Subs is msb(Max)+1,
    functor(Dyn, dyn, Subs).

dyn_access(I, Dyn, Value) :-
    must_be(positive_integer, I),
    I1 is msb(I),
    I11 is I1+1,
    I2 is I-(2**I1-1),
    debug(dyn, 'Located at index ~D in ~D', [I2, I11]),
    arg(I11, Dyn, A2),
    ( var(A2)
    -> Len is 2**I1,
        debug(dyn, 'Created sub array of length ~D for ~D', [Len, I11]),
        functor(A2, s, Len)
    ; true
    ),
    arg(I2, A2, Value).

```

Then we can run some tests and (by induction) conclude we are fine 🙂

```prolog
% Located at index 1 in 1
% Created sub array of length 1 for 1
X = dyn(s(1), _10312, _10314, _10316, _10318, _10320).

116 ?- dyn_new(32, X), dyn_access(2, X, 1).
% Located at index 1 in 2
% Created sub array of length 2 for 2
X = dyn(_10296, s(1, _10444), _10300, _10302, _10304, _10306).

117 ?- dyn_new(32, X), dyn_access(3, X, 1).
% Located at index 2 in 2
% Created sub array of length 2 for 2
X = dyn(_10296, s(_10442, 1), _10300, _10302, _10304, _10306).

118 ?- dyn_new(32, X), dyn_access(4, X, 1).
% Located at index 1 in 3
% Created sub array of length 4 for 3
X = dyn(_10300, _10302, s(1, _10448, _10450, _10452), _10306, _10308, _10310).

```

---

_[View the full topic](https://swi-prolog.discourse.group/t/does-swi-prolog-have-n-k-trees/1310)._
