Prolog Specific Article Grammar for IPv4 Address

I am currently trying to set up a small program to accept IPv4- capable four-line strings in SWI Prolog using DCGs (getting out of my comfort zone during the holidays, yes I can!). It will probably take me another hour or so, but perhaps one of the readers is already ready. In this case, I can attack the IPv6 address strings .

+3


source to share


2 answers


I'll try to answer SWISH, this snippet

Here is the code in case the link is unstable ...



:- use_module(library(dcg/basics)).

atom_ipv4(A, IPV4) :- atom_codes(A, Cs), phrase(ipv4(IPV4), Cs).

ipv4(D) -->
    dotted(D).
ipv4(range(D, R)) -->
    dotted(D), "/", integer(R).

dotted(address(A, B, C, D)) -->
    octet(A), ".", octet(B), ".", octet(C), ".", octet(D).

octet(A) --> integer(A), {A < 256}.

      

Note. Of course the spec is more complex than the one captured by this snippet as it allows hexadecimal and more ... my goal is to indicate library availability (dcg / basics)

+2


source


Answer # 2:



% Is the atom 'X' a valid IPv4 address?
% Transform the atom 'X' into a list of character codes, which is then processed

is_ipv4(X) :- string_codes(X,Codes), phrase(ipv4, Codes).

% Testing the above

test :- is_ipv4('127.0.0.1'),
    is_ipv4('255.255.255.255'),
    is_ipv4('10.10.10.1'),
    is_ipv4('0010.00010.000.0000'),
    \+is_ipv4('256.0.0.1'),
    \+is_ipv4('12.0.'),
    \+is_ipv4('').


% ----------------------
% Use Definite Clause Grammer to parse a list of character codes
% Subelements can be queried like this: 
% phrase(quadpart, `255`, []).
% phrase(pdigits(X,Y), `123`, []).

ipv4                     --> quadpart, dot, quadpart, dot, quadpart, dot, quadpart.
dot                      --> `.`.
quadpart                 --> pdigits(_,Q), { Q < 256 }.
pdigits(UpPower,UpValue) --> pdigit(Value), !, pdigits(DownPower, DownValue), { UpValue is DownPower*Value+DownValue, UpPower is DownPower*10 }.
pdigits(1,0)             --> [].
pdigit(Value)            --> [D], { code_type(D, digit(Value)) }.
% ---------------------

      

0


source







All Articles