Erlang - How to print list results on a new line? - erlang

I have the following function where it takes a list of integers and returns only the even numbers within that list.
even_print(List)->
[X||X <- List, even == even_odd(X)].
How can I print the results in a new line like this:
216> seq_erlang:even_print([2,4,5]).
2
4
instead of this:
216> seq_erlang:even_print2([2,4,5]).
[2,4]
I have used io:format("~p~n",X) inside my list comprehension but my variable X becomes unbound of course.

even_print(List)->
[io:format("Printing ~p ~n",[X])|| X <- List, even == even_odd(X)].
Now try:
217> seq_erlang:even_print([2,4,5]).
Printing 2
Printing 4
[ok,ok]

Related

Lua | Count Occurences of Each Item in a Table

hi I'm trying to convert this python code to Lua
names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
d={}
for i in range(len(names)-1):
x=names[i]
c=0
for j in range(i,len(names)):
if names[j]==names[i]:
c=c+1
count=dict({x:c})
if x not in d.keys():
d.update(count)
print (d)
I got all the other parts working from top but I couldn't figure out how to convert this part into Lua
if x not in d.keys():
d.update(count)
would be really great if someone can help me make sense of this conversion
if x not in d.keys():
d.update(count)
x is the name currently indexed in that loop cycle
d is a dictionary that is used to store the count of each name
c is a dictionary with a single entry, the count c of x in names
So that line basically says:
if the current name x has not been counted yet (is not in our dictionary), add its count c to d using the name in x as key.
This code is not very efficient as it counts the names every time, even if that name has already been counted. The order should be changed so you only count if there is no count in d, yet.
There is also no need to iterate over the whole array for each entry. That nested loop is nonsense. You can count that in one go.
You shouldn't learn from whatever resource that is.
In Lua the snippet above would look something like:
if not d[x] then d[x] = c end
or simply
d[x] = d[x] or c
This is how you could implement it in Lua efficiently.
local names= {'Deepak','Reema','John','Deepak','Munna','Reema','Deepak',
'Amit','John','Reema'}
local counts = {}
for _, v in ipairs(names) do
counts[v] = counts[v] and counts[v] + 1 or 1
end

Take every item in list that starts with x and put it in a new list - Rego

list := ["a:aqsdf", "a:asdf", "b:gfs", "b:sdf", "a:adfd", "b:asdfd"]
I want the new list to only include items that start with 'a': ["a:aqsdf", "a:asdf", "a:adfd"]
I've tried working with sets with no success. This would be a breeze in python but can't seem to wrap my head around rego. I can turn it into a set but not sure how to squeeze in an if statement(startswith(list[_], "a") == true)
One way to do this is with an array comprehension and the startswith builtin function:
[ x | x := list[_]; startswith(x, "a")]
Playground example: https://play.openpolicyagent.org/p/8mQYYvUL2h
This is essentially saying to define a new array containing the value of x if the rule body is true. The rule body for the comprehension is in turn iterating over all indicies of list for values of x, and will be true when the value of x starts with "a".
References:
https://www.openpolicyagent.org/docs/latest/policy-reference/#strings
https://www.openpolicyagent.org/docs/latest/policy-language/#comprehensions

What does (_,[]) mean?

I was given a question which was:
given a number N in the first argument selects only numbers greater than N in the list, so that
greater(2,[2,13,1,4,13]) = [13,4,13]
This was the solution provided:
member(_,[]) -> false;
member(H,[H|_]) -> true;
member(N,[_,T]) -> member(N,T).
I don't understand what "_" means. I understand it has something to do with pattern matching but I don't understand it completely. Could someone please explain this to me
This was the solution provided:
I think you are confused: the name of the solution function isn't even the same as the name of the function in the question. The member/2 function returns true when the first argument is an element of the list provided as the second argument, and it returns false otherwise.
I don't understand what "_" means. I understand it has something to do with pattern matching but I don't understand it completely. Could someone please explain this to me
_ is a variable name, and like any variable it will match anything. Here are some examples of pattern matching:
35> f(). %"Forget" or erase all variable bindings
ok
45> {X, Y} = {10, 20}.
{10,20}
46> X.
10
47> Y.
20
48> {X, Y} = {30, 20}.
** exception error: no match of right hand side value {30,
20}
Now why didn't line 48 match? X was already bound to 10 and Y to 20, so erlang replaces those variables with their values, which gives you:
48> {10, 20} = {30, 20}.
...and those tuples don't match.
Now lets try it with a variable named _:
49> f().
ok
50> {_, Y} = {10, 20}.
{10,20}
51> Y.
20
52> {_, Y} = {30, 20}.
{30,20}
53>
As you can see, the variable _ sort of works like the variable X, but notice that there is no error on line 52, like there was on line 48. That's because the _ variable works a little differently than X:
53> _.
* 1: variable '_' is unbound
In other words, _ is a variable name, so it will initially match anything, but unlike X, the variable _ is never bound/assigned a value, so you can use it over and over again without error to match anything.
The _ variable is also known as a don't care variable because you don't care what that variable matches because it's not important to your code, and you don't need to use its value.
Let's apply those lessons to your solution. This line:
member(N,[_,T]) -> member(N,T).
recursively calls the member function, namely member(N, T). And, the following function clause:
member(_,[]) -> false;
will match the function call member(N, T) whenever T is an empty list--no matter what the value of N is. In other words, once the given number N has not matched any element in the list, i.e. when the list is empty so there are no more elements to check, then the function clause:
member(_,[]) -> false;
will match and return false.
You could rewrite that function clause like this:
member(N, []) -> false;
but erlang will warn you that N is an unused variable in the body of the function, which is a way of saying: "Are you sure you didn't make a mistake in your function definition? You defined a variable named N, but then you didn't use it in the body of the function!" The way you tell erlang that the function definition is indeed correct is to change the variable name N to _ (or _N).
It means a variable you don't care to name. If you are never going to use a variable inside the function you can just use underscore.
% if the list is empty, it has no members
member(_, []) -> false.
% if the element I am searching for is the head of the list, it is a member
member(H,[H|_]) -> true.
% if the elem I am searching for is not the head of the list, and the list
% is not empty, lets recursively go look at the tail of the list to see if
% it is present there
member(H,[_|T]) -> member(H,T).
the above is pseudo code for what is happening. You can also have multiple '_' unnamed variables.
According to Documentation:
The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.
Example:
[H, _] = [1,2] % H will be 1
Also documentation says that:
Variables starting with underscore (_), for example, _Height, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they do not generate any warnings for unused variables.
Sorry if this is repetitive...
What does (_,[]) mean?
That means (1) two parameters, (2) the first one matches anything and everything, yet I don't care about it (you're telling Erlang to just forget about its value via the underscore) and (3) the second parameter is an empty list.
Given that Erlang binds or matches values with variables (depending on the particular case), here you're basically looking to a match (like a conditional statement) of the second parameter with an empty list. If that match happens, the statement returns false. Otherwise, it tries to match the two parameters of the function call with one of the other two statements below it.

Erlang list comprehension, once again

I'm trying to get a list comprehension working, which intention is to verify that each element X in List is followed by X+Incr (or an empty list). Later, I shall use that list and compare it with a list generated with lists:seq(From,To,Incr).
The purpose is to practice writing test cases and finding test properties.
I've done the following steps:
1> List.
[1,3,5,8,9,11,13]
2> Incr.
2
3> List2=[X || X <- List, (tl(List) == []) orelse (hd(tl(List)) == X + Incr)].
[1]
To me, it seem that my list comprehension only takes the first element in List, running that through the filter/guards, and stops, but it should do the same for EACH element in List, right?
I would like line 3 returning a list, looking like: [1,2,9,11,13].
Any ideas of how to modify current comprehension, or change my approach totally?
PS. I'm using eqc-quickcheck, distributed via Quviq's webpage, if that might change how to solve this.
The problem with your list comprehension is that List always refers to the entire list. Thus this condition allows only those X that are equal to the second element of List minus Incr:
(hd(tl(List)) == X + Incr)
The second element is always 3, so this condition only holds for X = 1.
A list comprehension cannot "look ahead" to other list elements, so this should probably be written as a recursive function:
check_incr([], _Incr) ->
true;
check_incr([_], _Incr) ->
true;
check_incr([A, B | Rest], Incr) ->
A + Incr == B andalso check_incr([B | Rest], Incr).
Maybe I'm misunderstanding you, but a list comprehension is supposed to be "creating a list based on existing lists". Here's one way to generate your list using a list comprehension without using lists:seq:
> Start = 1, Inc = 2, N = 6.
6
> [Start + X*Inc || X <- lists:seq(0,N)].
[1,3,5,7,9,11,13]
You could do something like this:
> lists:zipwith(fun (X, Y) -> Y - X end, [0 | List], List ++ [0]).
[1,2,2,2,2,2,2,-13]
Then check that all elements are equal to Incr, except the first that should be equal to From and the last that should be greater or equal than -To.
One quick comment is that the value List does NOT change when in the comprehension is evaluated, it always refers to the initial list. It is X which steps over all the elements in the list. This means that your tests will always refer to the first elements of the list. As a list comprehension gives you element of a list at a time it is generally not a good tool to use when you want to compare elements in the list.
There is no way with a list comprehension to look at successive sublists which is what you would need (like MAPLIST in Common Lisp).

What does [ ... || ... <- ...] do in this snippet of code?

I need your help again, I am trying to understand this piece of erlang code.
Line="This is cool".
Lines = [Line || _Count <- lists:seq(1,5)].
output is
["This is cool","This is cool","This is cool","This is cool","This is cool"]
I don't understand the logic behind it printing the required number of times. What does Line || _***** means?
Since the value of Line is not changed in the right hand side of the list comprehension, the value of each element is the same, the value of Line.
The right side of the list comprehension is just determining the number of elements.
Look at this piece of code:
Line = "This is cool".
Lines = [{Line, Count} || Count <- lists:seq(1, 5)].
Here you create a list of tuples of size 2 where first element is constant and the second is taken from the source list of list comprehension. And if you remove an element from the tuple it won't change list's structure.
it can be read like this: NewListe = [Dosomething || Element <- Liste]
create a NewListe this way: for each Element of Liste, build a new element with Dosomething.
Step by step it gives Liste = lists:seq(1,5) = [1,2,3,4,5];
for each Element, just discard the value of element (it is why it is written as _Count) and
Dosomething is only send back the value "This is cool",
and the result is a list of 5 times "This is cool"
["This is cool","This is cool","This is cool","This is cool","This is cool"]
<- is called a generator; after the sign || you may have generators or filters. For example if we imagine that you have a list of different elements and want to get only the printable list items, turned to upper case, you will need a generator:
X <- ["toto",5,"Hello",atom] to get each element
a filter:
io_lib:printable_list(X) to select only the printable lists
and a transformation:
string:to_upper(X) to turn to upper case
all together you have what is expected:
1> [string:to_upper(X) || X <- ["toto",5,"Hello",atom], io_lib:printable_list(X)].
["TOTO","HELLO"]
2>

Resources