How to print this in one line statement in Prolog - printing

How can i print this string in prolog in the best way:
predicate([], L, Id, L2):-
length(L2, N),
write('The length '),
write(Id),
write(' is '),
write(N),
write(' elements.'),
nl.

In SWI-Prolog, you can use the built-in predicate format/2:
predicate([], L, Id, L2):-
length(L2, N),
format('The length of ~w is ~w elements\n', [Id, N]).

Related

How to eliminate the quotation marks of a list of strings?

I receive the following list of strings from a text file:
["{0988070979,APP03#media}","{0988070978,APP01#media}","{0988070977,APP02#media}"]
I need the same list but without the quotation marks ( " " ), something like this:
[{0988070979,APP03#media},{0988070978,APP01#media},{0988070977,APP02#media}]
1> L = ["{0988070979,APP03#media}","{0988070978,APP01#media}","{0988070977,APP02#media}"].
["{0988070979,APP03#media}","{0988070978,APP01#media}",
"{0988070977,APP02#media}"]
2> [{N, M} || X <- L, [N, M] <- [string:tokens(X, "{},")]].
[{"0988070979","APP03#media"},
{"0988070978","APP01#media"},
{"0988070977","APP02#media"}]
or (not recommended)
3> [{list_to_integer(N), list_to_atom(M)} || X <- L, [N, M] <- [string:tokens(X, "{},")]].
[{988070979,'APP03#media'},
{988070978,'APP01#media'},
{988070977,'APP02#media'}]
and so on.
You should use erl_scan module to tokenize the string and erl_parse to convert the tokens to a erlang term.
let your strings be Str
{ok, Ts, _} = erl_scan:string(Str).
{ok, Tup} = erl_parse:parse_term(Ts).
The Tup is the Tuples you need ...

replacing a value withgsub in lua

function expandVars(tmpl,t)
return (tmpl:gsub('%$([%a ][%w ]+)', t)) end
local sentence = expandVars("The $adj $char1 looks at you and says, $name, you are $result", {adj="glorious", name="Jayant", result="the Overlord", char1="King"})
print(sentence)
The above code work only when I have ',' after the variable name like, in above sentence it work for $ name and $ result but not for $adj and $char1, Why is that ?
Problem:
Your pattern [%a ][%w ]+ means a letter or space, followed by at least one letter or number or space. Since regexp is greedy, it will try to match as large a sequence as possible, and the match will include the space:
function expandVars(tmpl,t)
return string.gsub(tmpl, '%$([%a ][%w ]+)', t)
end
local sentence = expandVars(
"$a1 $b and c $d e f ",
{["a1 "]="(match is 'a1 ')", ["b and c "]="(match is 'b and c ')", ["d e f "]="(match is 'd e f ')", }
)
This prints
(match is 'a1 ')(match is 'b and c ')(match is 'd e f ')
Solution:
The variable names must match keys from your table; you could accepts keys that have spaces and all sort of characters but then you are forcing the user to use [] in the table keys, as done above, this is not very nice :)
Better keep it to alphanumeric and underscore, with the constraint that it cannot start with a number. This means to be generic you want a letter (%a), followed by any number of (including none) (* rather than +) of alphanumeric and underscore [%w_]:
function expandVars(tmpl,t)
return string.gsub(tmpl, '%$(%a[%w_]*)', t)
end
local sentence = expandVars(
"$a $b1 and c $d_2 e f ",
{a="(match is 'a')", b1="(match is 'b1')", d_2="(match is 'd_2')", }
)
print(sentence)
This prints
(match is 'a') (match is 'b1') and c (match is 'd_2') e f; non-matchable: $_a $1a b
which shows how the leading underscore and leading digit were not accepted.

Erlang: proplists:get_value/2 or pattern matching?

I have a list of tuples that has always the same form (i.e. the tuples come always in the same order):
1> L = [{a, 1}. {b,2}, {c, 3}, {d, 4}].
Knowing that the list has only a few elements, what is the best way to extract the values associated to the keys?
Suppose the list is passed as argument to a function, to extract the values should I use:
proplists:get_value(a, L).
proplists:get_value(b, L).
...
proplists:get_valus(d, L).
Or should I simply use pattern matching as:
[{a, 1}. {b,2}, {c, 3}, {d, 4}] = L.
If you really know your lists is in same form pattern matching is simplest
[{a, A}, {b, B}, {c, C}, {d, D}] = L,
you can compare it with following
[A, B, C, D] = [ proplists:get_value(X, L) || X <- [a,b,c,d] ],
or
A = proplists:get_value(a, L),
B = proplists:get_value(b, L),
C = proplists:get_value(c, L),
D = proplists:get_value(d, L),
or
[A, B, C, D] = [ V || Key <- [a,b,c,d], {K, V} <- L, K =:= Key ],
Pattern matching will be also fastest. You can also use lists:keyfind/3 which is implemented as Bif and is way faster than proplist:get_value/2 but it doesn't matter for short lists.

Scala parser combinators for (almost) trivial grammar

I've been trying to make a parser for a (very) simple language that looks like this:
block{you are a cow too blkA{ but maybe not} and so is he} hear me moo blockZ{moooooo}
I can break it apart using regexes:
.*?[^ ]*?\\{
.*?\\}
which would essentially keep eating characters until it found something that matches [^ ]*?\\{ or \\}: the start or end of a block. My question is, if I want to do it using Scala's Parser Combinators, how do I do that? I currently have:
def expr: Parser[Any] = (block | text)+
def text = ".+?".r
def block = "[^ ]*?\\{".r ~ expr ~ "}"
but this doesn't work:
parsed: List(b, l, o, c, k, {, y, o, u, a, r, e, a, c, o, w, t, o, o, b, l, k, A, {, b, u, t, m, a, y, b, e, n, o, t, }, a, n, d, s, o, i, s, h, e, }, h, e, a, r, m, e, m, o, o)
It seems that the block parser is not firing, and so the text parser is being fired repeatedly. but when i remove the text parser:
def expr: Parser[Any] = (block)+
I get:
failure: string matching regex `[^ ]*?\{' expected but `y' found
block{you are a cow too blkA{ but maybe not} and so is he} hear me moo
^
So obviously the block parser does work, except not when the text parser is present. What's happening? and is there a "proper" way of doing this, for so basic a grammar?
EDIT: Changed the title, since it's not so much about the reluctance anymore as just solving the problem
EDIT: I now have this:
def expr: Parser[Any] = (block | text)+
def text = "[^\\}]".r
def block = "[^ ]*?\\{".r ~ expr ~ "}"
The logic behind this is that for each character, it tests whether or not it is the start of a block. If it isn't, it moves on to the next character. This gives me:
parsed: List(((block{~List(y, o, u, a, r, e, a, c, o, w, t, o, o, ((blkA{~List(b, u, t, m, a, y, b, e, n, o, t))~}), a, n, d, s, o, i, s, h, e))~}), h, e, a, r, m, e, m, o, o)
which is kind of correct. It is parsing the non-block characters one-by-one though, which is probably a performance problem (i think?). Is there any way to parse all those non-block characters at once and leave them in one big string?
The problem is that text is consuming all closing curly braces (}). It goes like this:
expr -> block -> expr -> text.+ (until all input is consumed)
At this point, it exits expr and tries to parse }, which does not exists, fails, and falls back to text on the first expr.
You can use log to see what's going on when you parse.

What does the "head mismatch" compiler error mean?

I tries to write code to print Z character.
zzzzzzz
z
z
z
z
z
zzzzzzz
But when I compile this code, it throws
D:\erlang\graphics>erlc zeez2.erl
d:/erlang/graphics/zeez2.erl:19: head mismatch
d:/erlang/graphics/zeez2.erl:6: function zeez/3 undefined
I can't fixed this error. I didn't find what wrong in my could.
Does one please suggest me.
Thank you.
-module(zeez2).
-export([main/0]).
main() ->
L = 8,
zeez( false ,1, L). % line 6
zeez(true, M,M) ->
init:stop();
zeez(false, M, N) ->
io:format("~p~n", [zeez(z, N-M)] ),
zeez(M rem N =:= 0, M + 1, N );
zeez(true, M, N) ->
io:format("~p~n", [zeez(space, N-M)] ), % line 16
zeez(M rem N =:= 0, M + 1 , N );
zeez(space, M) ->
io:format("~p~n", ["-" ++ zeez(space, M-1)] );
zeez(space, 0) ->
"Z";
zeez(z, M) ->
io:format("~p~n", ["Z" ++ zeez(z, M-1)] );
zeez(z,0) ->
"Z".
the problem is that you have mixed up 2 functions:
zeez/2 and zeez/3
If you terminate the zeez/3 function by ending it with a full stop not a semi-colon it should compile:
zeez(true, M, N) ->
io:format("~p~n", [zeez(space, N-M)] ), % line 16
zeez(M rem N =:= 0, M + 1 , N ); <-- should end with .
The error message means, 'hey I'm in zeez/3 and you have thrown in a 2-arity clause, wtf?'
You're trying to define two functions, the first with 3 parameters (zeez/3) and another with 2 parameters (zeez/2). The head mismatch error is because the zeez/3 function on the previous line should be terminated with a '.'.
I.e. because you've ended the previous zeez/3 function with a ';', it expects the following declaration to be another match for zeez/3:
zeez(true, M, N) ->
io:format("~p~n", [zeez(space, N-M)] ), % line 16
zeez(M rem N =:= 0, M + 1 , N ).
zeez(space, M) ->
io:format("~p~n", ["-" ++ zeez(space, M-1)] );
You should also note that the compiler will give you warnings about "... previous clause at line xxx always matches" because of the ordering of zees(space, 0) and zeez(space, M). You should put zees(space, 0) before zeez(space, M), because it is more specific.

Resources