| Did you know ... | Search Documentation: |
| Predicate type_error/2 |
type_error(+ValidType,
+Culprit)Suppose an argument must be a non-negative integer. If the actual argument is not an integer, this is a type_error. If it is a negative integer, it is a domain_error.
Typical borderline cases are predicates accepting a compound term,
e.g., point(X,Y). One could argue that the basic type is a
compound-term and any other compound term is a domain error. Most Prolog
programmers consider each compound as a type and would consider a
compound that is not point(_,_) a type_error.
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.