Here is my translation of Python from Wikipedia
is_luhn_valid(Card_number):-
luhn_checksum(Card_number, 0).
luhn_checksum(Card_number, Checksum) :-
digits_of(Card_number, Digits),
findall(D, (nth0(I, Digits, D), I mod 2 =:= 0), Odd_digits),
findall(D, (nth0(I, Digits, D), I mod 2 =:= 1), Even_digits),
sum_list(Odd_digits, Checksum_t),
findall(S, (
member(T, Even_digits),
T1 is T * 2,
digits_of(T1, D1),
sum_list(D1, S)
), St),
sum_list(St, St1),
Checksum is (Checksum_t + St1) mod 10.
digits_of(Number, Digits) :-
number_codes(Number, Cs),
maplist(code_digit, Cs, Digits).
code_digit(C, D) :- D is C - 0'0.
apart being more verbose, it seems to be correct wrt the test case from the above page. But:
?- is_luhn_valid(123).
false.
while your code:
?- luhn(123).
true ;
true ;
...
and, of course
?- luhn(124).
....
doesn't terminate. So, you're stick in a failure loop, where Prolog is asked every time to try to prove an unsolvable goal...
A fragment of trace:
?- leash(-all),trace.
true.
[trace] ?- luhn(124).
Call: (7) so:luhn(124)
Call: (8) so:spliter(124, _G9437)
...
Exit: (8) 2 is 12 mod 10
Call: (8) 2 is 0
Fail: (8) 2 is 0
Redo: (11) so:spliter(0, _G9461)
Call: (12) _G9465 is floor(0/10)
...
The problem seems to be that spliter/2 keeps adding 0s in front of the sequence, while it should fail instead.
About efficiency: my snippet can be rewritten as
luhn_checksum(Card_number, Checksum) :-
digits_of(Card_number, Digits),
aggregate_all(sum(V), (
nth0(I, Digits, D),
( I mod 2 =:= 0
-> V = D % Odd_digits
; Dt is D * 2, % Even_digits
digits_of(Dt, Ds),
sum_list(Ds, V)
)),
Checksum_t),
Checksum is Checksum_t mod 10.
making use of library(aggregate)
edit
I think spliter/2 should check if N>0, otherwise it will recurse forever...
try
spliter(N,L):- N>0,
N1 is floor(N/10),
...