Home > Net >  Splitting a list into two sublists with one having a predefined length
Splitting a list into two sublists with one having a predefined length

Time:12-25

I'm new to Prolog and I have this code. I would like it to split a list into two lists or sublists where the first sublist/ list is of a predefined length and the other one contains the rest of the elements. Here's the code. `

list_length([],0).
list_length([_|T],N):- list_length(T, N1), N is N1   1.
div(L, A, B, N) :-
    append(A, B, L),
    length(A, N),
    length(B, N).

div(L, A, B, N) :-
    append(A, B, L),
    length(A, N),
    N1 is N   1,
    length(B, N1).

div(L, A, B, N) :-
    append(A, B, L),
    length(A, N),
    N1 is N - 1,
    length(B, N1).

`` When I run my above code, it returns an error saying: ERROR: Unknown procedure: (div)/4 ERROR: However, there are definitions for: ERROR: (div)/3 false.

I would like the input to be this:

`?- div([44,55,23,86,49,94,30,77], L1, L2, 6).
    L1 = [44,55,23,86,49,94]
    L2 = [30,77]

Help me understand what I am doing wrong.

CodePudding user response:

Help me understand what I am doing wrong.

You should be using length/2 and append/3, one after the other, like this:

div(L, A, B, N) :-
    append(A, B, L),
    length(A, N).

This is all.

Do not define your own length/2.

But you have not shown how you compile and evaluate your code. For example, I get:

?- [user].
|: div(L, A, B, N) :- append(A, B, L), length(A, N).
|: ^D% user://1 compiled 0.01 sec, 1 clauses
true.

?- div([a,b,c,d], A, B, 2).
A = [a, b],
B = [c, d] ;
false.

?- div([a,b,c,d], [X,Y], B, N).
X = a,
Y = b,
B = [c, d],
N = 2.

?- div([a,b,c,d], A, [X,Y,Z], N).
A = [a],
X = b,
Y = c,
Z = d,
N = 1 ;
false.

?- div([a,b], A, B, N).
A = [],
B = [a, b],
N = 0 ;
A = [a],
B = [b],
N = 1 ;
A = [a, b],
B = [],
N = 2 ;
false.

?- div(L, A, B, N).
L = B,
A = [],
N = 0 ;
L = [_A|B],
A = [_A],
N = 1 ;
L = [_A, _B|B],
A = [_A, _B],
N = 2 .

Since I made that mistake already, it is worth asking: Can you switch the order of append and length in the definition? What happens if you do?

  • Related