0

I need some help to understand what is this below function doing?

func([], R, _, R).

func([_,_|F], [H|S], Pre, [Pre|B]) :-
    func(F, S, H, B).
Dev
  • 576
  • 3
  • 14

1 Answers1

1

This predicate is probably most useful as a helper predicate. It can be used to remove the middle element of a list. Note that only a list with an odd number of elements has a middle element.

If I squint, I can see an "F" and an "S" there in the argument names. Could that stand for "Fast" and "Slow"? Difficult to tell without further information. The two arguments could also be named "H" and "T", for "Hair" and "Tortuous", but this is too confusing, since the "H" and "T" usually stand for "Head" and "Tail", as in, "The hare was biting its own tale".

But first, you need to add the real predicate that uses this helper predicate. I will call it "fun" because it has one letter less than "funk" and everyone loves to have fun. "R" stands for "Result" or "Rest" because you might need a rest after you work to get your result.

fun([X|Xs], R) :-
    func(Xs, Xs, X, R).

func([], R, _, R).

func([_,_|F], [H|S], Pre, [Pre|B]) :-
    func(F, S, H, B).

Now you can remove the middle element, or do other things which are somehow related to that:

?- fun([a,b,c], R).
R = [a, c].

?- fun([a], R).
R = [].

?- fun(L, [a,b]), numbervars(L).
L = [a, A, b] ;
false.

?- fun(L, [a|X]), numbervars(L-X).
L = [a, A, B],
X = [B] ;
L = [a, A, B, C, D],
X = [A, C, D] ;
L = [a, A, B, C, D, E, F],
X = [A, B, D, E, F] .

Almost forgot: take a look at this question, it seems to be related to your question.

TA_intern
  • 2,222
  • 4
  • 12