A very simple solution:
before( _, [], []).
before( N, [N|_], [N]).
before( N, [X|T], [X|Res]):- dif(N,X), before( N, T, Res).
Example:
?- before(5, [1, 2, 4, 5, 36, 5], Result).
Result = [1, 2, 4, 5] ;
false.
And a more elegant solution using if_/3
from library(reif)
:
:- use_module(library(reif)).
before( _, [] , [] ).
before( N, [X|T], Res):-
if_( X = N,
Res = [N],
(before( N, T, Res2), Res = [X|Res2] )
).
Example:
?- before(5, [1, 2, 4, 5, 36, 5], Result).
Result = [1, 2, 4, 5].
As you can see this is deterministic it only gave one answer and no choice point left. In the first answer same result was given but there was a choice point returning false. This second answer which gives right result avoiding this useless choice point is more efficient. Also in