Did you know ... | Search Documentation: |
![]() | Predicate ,/2 |
Goal1, Goal2 :- Goal1, Goal2.
is_odd(I) :- 0 =\= I mod 2.
?- numlist(1, 6, List), include(is_odd, List, Odd). List = [1, 2, 3, 4, 5, 6], Odd = [1, 3, 5].
?- length(L, 3), maplist(between(0, 1), L). L = [0, 0, 0] ; L = [0, 0, 1] ; L = [0, 1, 0] ; L = [0, 1, 1] ; L = [1, 0, 0] ; L = [1, 0, 1] ; L = [1, 1, 0] ; L = [1, 1, 1].
?- length(L, 5), maplist(=(foo), L). L = [foo, foo, foo, foo, foo].
Normally used to update the value associated with a key. For example, if the value is a count that must be incremented, do
inc_count(Key, A0, A) :- get_assoc(Key, A0, C0, A, C), !, C is C0+1. inc_count(Key, A0, A) :- put_assoc(Key, A0, 1, A).
This shows how to convert almost any "string" of 0s and 1s to an integer.
It takes advantage of the built-in term reading, thus avoiding an explicit loop and arithmetic.
binary_string_to_int(Str, Int) :- ( ( string(Str) ; atom(Str) ) -> atomics_to_string(["0b", Str], Literal) ; is_list(Str) -> atomics_to_string(["0b"|Str], Literal) ; type_error(string_type, Str) ), catch(term_string(Int, Literal, []), error(syntax_error(_), _), type_error(string_of_0s_and_1s, Str)).
?- binary_string_to_int('101', X). X = 5. ?- binary_string_to_int([0, 0, 1, 0, 1], X). X = 5. ?- binary_string_to_int(["1", "1", "0"], X). X = 6.
The append/3 predicate can be used to split and join lists. We can combine that to realise substituting all appearances of a sublist into another as illustrated below.
append(This, After, Rest)
creates a pattern from This,
i.e., the list Rest starts with This.append(Before, Rest, MyStr)
matches the pattern against the
input list. On a match we commit (!). Now Before is the
input list before the match and After is the input list
after the match.subst(This, That, MyStr, Result) :- append(This, After, Rest), append(Before, Rest, MyStr), !, subst(This, That, After, AfterResult), append([Before,That,AfterResult], Result). subst(_, _, S, S).
?- portray_text(true). true. ?- subst(`this`,`that`,`athishellothis`,R). R = `athathellothat`.
word_frequency_count(Words, Counts) :- maplist(downcase_atom, Words, LwrWords), msort(LwrWords, Sorted), clumped(Sorted, Counts).
?- word_frequency_count([a,b,'A',c,d,'B',b,e], Counts). Counts = [a-2, b-3, c-1, d-1, e-1].