読者です 読者をやめる 読者になる 読者になる

差分リストの練習 その2

prolog

同期同士の勉強会でお題をもらった!

zip

list_heads(Lists, Hs, Rs) :- list_heads_sub(Lists, Hs, Rs), !.
list_heads(_, [], []).
list_heads_sub([[H | R] | Ls], [H | Hs], [R | Rs]) :-
        H \== [], list_heads_sub(Ls, Hs, Rs).
list_heads_sub(_, [], []).

zip(Lists, Result) :- zip_sub(Lists, [Result, []]).
zip_sub(Lists, [Result, Tail]) :-
        Lists \== [],
        list_heads(Lists, Hs, Rs),
        Hs \== [],
        [Result, Appender1] = [[Hs | Appender1], Appender2],
        zip_sub(Rs, [Appender2, Tail]), !.
zip_sub(_, [Tail, Tail]).

実行例

| ?- list_heads([[a,a],[b,a], [c,a]], Hs, Rs), list_heads(Rs, Hs1, Rs1).
list_heads([[a,a],[b,a], [c,a]], Hs, Rs), list_heads(Rs, Hs1, Rs1).

Hs = [a,b,c]
Hs1 = [a,a,a]
Rs = [[a],[a],[a]]
Rs1 = [[],[],[]]

(4 ms) yes
| ?- list_heads([[a],[b], [c]], Hs, Rs), list_heads(Rs, Hs1, Rs1).
list_heads([[a],[b], [c]], Hs, Rs), list_heads(Rs, Hs1, Rs1).

Hs = [a,b,c]
Hs1 = []
Rs = [[],[],[]]
Rs1 = []

yes
| ?- list_heads([[],[b], [c]], Hs, Rs)
list_heads([[],[b], [c]], Hs, Rs).

Hs = []
Rs = []

yes
| ?- zip([[a,a],[b,b], [c,c]], Hs).
zip([[a,a],[b,b], [c,c]], Hs).

Hs = [[a,b,c],[a,b,c]]

yes
| ?- zip([[a,a],[b,b,b], [c,c]], Hs).
zip([[a,a],[b,b,b], [c,c]], Hs).

Hs = [[a,b,c],[a,b,c]]

(4 ms) yes
| ?- zip([[],[], []], Hs).
zip([[],[], []], Hs).

Hs = []

(4 ms) yes
| ?- zip([], Hs).
zip([], Hs).

Hs = []

yes
| ?-
zip 修正

listを見る必要はなかった。

zip(Lists, Result) :- zip_sub(Lists, [Result, []]).
zip_sub(Lists, [Result, Tail]) :-
        list_heads(Lists, Hs, Rs),
        Hs \== [],
        [Result, Appender1] = [[Hs | Appender1], Appender2],
        zip_sub(Rs, [Appender2, Tail]), !.
zip_sub(_, [Tail, Tail]).
list_heads 修正

Hを見る必要もなかった。

list_heads(Lists, Hs, Rs) :- list_heads_sub(Lists, Hs, Rs), !.
list_heads(_, [], []).
list_heads_sub([[H | R] | Ls], [H | Hs], [R | Rs]) :- list_heads_sub(Ls, Hs, Rs).
list_heads_sub(_, [], []).

last

うまく作れない。。。動かないコードをはっとく

/* 動かない。。。 */
my_last([_ | Rest], Result) :- my_last(Rest, Result).
my_last([Result | []], Result).