Erlang record expression ignored warning stopping answer - erlang

I have following code:
M =list:sort([X|Y]), list:sort(length) / 2,io:format("The median of the items is", [M]),
But I get warning when I try to compile it:
Warning: the result of the expression is ignored (suppress the warning by assigning the expression to the _ variable)
What's wrong? How can i fix it?
This is it within my surrounding code and its the only problem with my program. Everything else works.
answer([ ]) -> io:format(" There are no items in the list");
answer([X|Y]) ->
M =list:sort([X|Y]), list:sort(length) / 2,io:format("The median of the items is", [M]),

in your code, list:sort(length) will fail as length is an atom and the function is looking for a list, and the io:format/2 format string is missing a place holder to print the result.
the following code works, al least it prints the results, but it always return ok.
answer([ ]) -> io:format("There are no items in the list~n");
answer(L) when is_list(L) -> io:format("The median of the items is ~p~n",
[lists:nth((length(L)+1) div 2,lists:sort(L))]);
answer(_) -> io:format("error,the input parameter is not a list~n").
some example of use directly entered in the console. You can see that it will give an answer which can seem weird, while technically correct, when the list contains other element than numbers.
1> Answer = fun([ ]) -> io:format("There are no items in the list~n");
1> (L) when is_list(L) -> io:format("The median of the items is ~p~n",
1> [lists:nth((length(L)+1) div 2,lists:sort(L))]);
1> (_) -> io:format("error,the input parameter is not a list~n") end.
#Fun<erl_eval.6.80484245>
2> L1 = [6,9,5,7,8].
[6,9,5,7,8]
3> Answer(L1).
The median of the items is 7
ok
4> L2 = [4,6,3].
[4,6,3]
5> Answer(L2).
The median of the items is 4
ok
6> L3 = [4,6,3,8].
[4,6,3,8]
7> Answer(L3).
The median of the items is 4
ok
8> L4 = [hello, 5,[1,2]].
[hello,5,[1,2]]
9> Answer(L4).
The median of the items is hello
ok
10> Answer("test_string").
The median of the items is 114
ok
11> Answer(test_atom).
error,the input parameter is not a list
ok
12> Answer("").
There are no items in the list
ok
13>

Related

Erlang: How do you return an element of a list?

For example: [{a,b},{c,d},{e,f}]. I want to pick on the list with an argument (being c) and it will return d.
You can use few approaches or use Erlang functions from the standard library(like lists etc.) or you can create your own, eg:
List Comprehensions
1> List = [{a,b}, {c,d}, {e,f}].
2> Being = e.
3> [Result] = [Y || {X, Y} <- List, Being =:= X].
4> Result.
f
Functions
1> GetVal = fun GetVal (_, []) -> not_found;
GetVal (X, [{X, Result} | _]) -> Result;
GetVal (X, [_ | T]) -> GetVal(X, T)
end.
2> List = [{a,b}, {c,d}, {e,f}].
3> Being = e.
4> GetVal(Being, List).
f
The simple way to use Pattern Matching and List Handling.
Write a program that prints each tuple in the list.
Write a program that prints just the second element of each tuple in the list.
Write a program that takes an argument Target along with a List. When you find the tuple {Target, Right}, print our Right.
If you don't mind using functions from the standard library, you can use lists:keyfind/2 or proplists:get_value/2,3.

write a function that, given a list, will drop every other element, starting by dropping the first element

Im working on some erlang functions and im also not allowed to use library functions. I have to define a function that drops every other element from a list, starting with the first element.
I have worked on something similar before but i could use BIFs and now i am struggling.
For example, alternate([1,2,3,four,5,6]) is [2,four,6]. I am not sure how to implement it.
spec drop_word(string()) -> string().
drop_word([]) -> [];
drop_word([O|Op]) -> case wsp(O) of
true -> Op;
false -> drop_word(Op)
end.
alternate(List) ->
alternate(List, _Index=0).
alternate([_|T], Index) when Index rem 2 == 0 -> %even indexes
alternate(T, Index+1);
alternate([H|T], Index) when Index rem 2 == 1 -> %odd indexes
[H | alternate(T, Index+1)];
alternate([], _Index) ->
[].
In the shell:
12> a:alternate([1,2,3,four,5,6]).
[2,four,6]
13> a:alternate([1,2,3,four,5]).
[2,four]
But, that can be simplified to:
alternate(List) ->
evens(List).
evens([_|T]) ->
odds(T);
evens([]) -> [].
odds([H|T]) ->
[H | evens(T)];
odds([]) -> [].
In the shell:
6> a:alternate([1,2,3,four,5,6]).
[2,four,6]
7> a:alternate([1,2,3,four,5]).
[2,four]
Here's an accumulator version:
alternate(List) ->
evens(List, []).
evens([_|T], Acc) ->
odds(T, Acc);
evens([], Acc) ->
lists:reverse(Acc).
odds([H|T], Acc) ->
evens(T, [H|Acc]);
odds([], Acc) ->
lists:reverse(Acc).
In the shell:
20> a:alternate([1,2,3,four,5,6]).
[2,four,6]
21> a:alternate([1,2,3,four,5]).
[2,four]
Note that lists:reverse() is highly optimized, so you would never do List ++ [X] many times, which traverses the whole list every time you add an element to the end of the list. Rather, you should always choose to add an element to the head of a list, then call lists:reverse(). Oh yeah, no library functions...a reverse() function is easy to implement yourself, and although it won't be optimized like the erlang version, it will still be more efficient than doing List ++ [X] multiple times.
You can use two atoms drop and keep two match the alternating clauses of do_alternate. Details below in comments.
-module(so).
-export([alternate/1]).
% The exported function starts the actual function and tells it to match the `drop`
% clause. Kept elements of L will be collected in the third argument.
alternate(L) -> do_alternate(drop, L, []).
% The `drop` clause will call the `keep` clause and pass the tail T and the
% currently collected list Acc. The head H will be dropped.
do_alternate(drop, [_|T], Acc) -> do_alternate(keep, T, Acc);
% The `keep` clause will call the `drop` claues and pass the tail T and the
% currently collected list Acc with the head H prepented to it.
do_alternate(keep, [H|T], Acc) -> do_alternate(drop, T, Acc ++ [H]);
% If the arugment list is empty, return the accumulated list.
do_alternate(_, [], Acc) -> Acc.
Example usage:
> c(so).
{ok,so}
9> so:alternate([1,2,3,4,5,6]).
[2,4,6]
10> so:alternate([1,2,3,4,5,6,seven,eight,nine,ten,eleven]).
[2,4,6,eight,ten]
It seems that you want to drop any elements with position which is even. So you can do it like below:
-module(test).
-compile([export_all,debug_info]).
alternate(L) -> do_alternate(L, 0, length(L)).
do_alternate(_, L, L) -> [];
do_alternate([H|T], N, L) ->
case (N band 1) == 0 of
true -> do_alternate(T, N+1, L);
false -> [H] ++ do_alternate(T, N+1, L)
end.
Result in shell:
1> c(test).
test.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,test}
2> test:alternate([1,2,3,four,5,6]).
[2,four,6]
Moreover, if your List only has integer numbers, so you can use BIF like below:
3> lists:partition(fun(A) -> A rem 2 == 1 end, [1,2,3,4,5,6]).
{[1,3,5],[2,4,6]}
You could pattern match on the list, taking two elements at a time:
alternate([_Odd, Even | T]) ->
[Even] ++ alternate(T);
alternate([]) ->
[].
The specification doesn't say what happens if the list has an odd number of elements, so this function will just crash with a "function clause" error in that case. You could add a third clause to handle that - presumably dropping the last element would be a sensible thing to do:
alternate([_Last]) ->
[];

Erlang: do list comprehension filters short circuit

Lets say I have:
[ X || X<- L, some_expensive_boolean(X), some_expensive_boolean2(X)]
If, for any X in L, some_expensive_boolean(X) is false, is some_expensive_boolean2(X) executed?
TL;DR: No, some_expensive_boolean2/1 is not called.
There a couple of ways you can verify this.
1. Having functions print something as they are called.
-module(lc).
-export([lc/1]).
lc(L) ->
[X || X <- L, f(X), g(X)].
f(X = 2) ->
erlang:display({f, 2}),
false;
f(X) ->
erlang:display({f, X}),
true.
g(X) ->
erlang:display({g, X}),
true.
Then on the Erlang shell:
1> lc:lc(lists:seq(1, 4)).
{f,1}
{g,1}
{f,2} %% g is not called here
{f,3}
{g,3}
{f,4}
{g,4}
[1,3,4]
2. Check the generated Core Erlang code.
Compiling the module with the +to_core option will produce a lc.core file with the Core Erlang code, which looks a little bit like Erlang but has its own syntax but very similar semantics.
erlc +to_core lc.erl
The code generated is quite verbose so I won't paste it here, but the gist is that there are two nested case expressions, one calling f/1 with the clause that matches on true containing the other case that calls g/1.
The answer is no. It is short-circuited.
1> [ X || X <-[1,2], begin io:format("Test 1: ~p~n", [X]), X rem 2 =:= 0 end, io:format("Test 2: ~p~n", [X]) =:= ok ].
Test 1: 1
Test 1: 2
Test 2: 2
[2]
Short-circuits based on the following:
-module(shortcircuit).
-export([test/0]).
test() ->
L = [1, 2, 3],
[ X || X <- L, some_expensive_boolean(X), some_expensive_boolean2(X)].
some_expensive_boolean(X) ->
io:format("In some_expensive_boolean: ~p~n", [X]),
false.
some_expensive_boolean2(X) ->
io:format("In some_expensive_boolean2: ~p~n", [X]),
true.
Execute:
1> shortcircuit:test().
In some_expensive_boolean: 1
In some_expensive_boolean: 2
In some_expensive_boolean: 3
[]
2>
Let's create an example:
$ cat test.erl
-module(test).
-export([show/0]).
show() ->
[ X || X <- [1,2,3,4,5], bigger(X), smaller(X)].
bigger(X) ->
io:format("bigger ~p~n", [X]),
X > 2.
smaller(X) ->
io:format("smaller ~p~n", [X]),
X < 4.
and test it:
14> c(test).
{ok,test}
15> test:show().
bigger 1
bigger 2
bigger 3
smaller 3
bigger 4
smaller 4
bigger 5
smaller 5
[3]
So the answer is: NO.

Remove list element occur only once

I have a list in erlang containing interger values.
I want to remove values that occur only one time.(Not Duplicates).
Input = [1,3,2,1,2,2]
Output = [1,2,1,2,2]
I am newbie to erlang. I have tried an approach to sorting them first using list:sort() and then removing a member if the member next to it is the same.
I am having trouble trying to iterate the list. It would be great help if you can show me how I can do it.
multiple(L) ->
M = L -- lists:usort(L),
[X || X <- L , lists:member(X,M)].
Use map to count values and then filter values which was not present just once.
-module(test).
-export([remove_unique/1]).
remove_unique(L) ->
Count = lists:foldl(fun count/2, #{}, L),
lists:filter(fun(X) -> maps:get(X, Count) =/= 1 end, L).
count(X, M) ->
maps:put(X, maps:get(X, M, 0) + 1, M).
And test:
1> c(test).
{ok,test}
2> test:remove_unique([1,2,3,3,3,5,5,6,7,7]).
[3,3,3,5,5,7,7]
3> test:remove_unique([1,2,3,3,3,5,5,6,7,8]).
[3,3,3,5,5]
4> test:remove_unique([1,3,2,1,2,2]).
[1,2,1,2,2]
Here's a solution I'd written when first seeing the question when posted, that uses the same logic as #A.Sarid's recursion/pattern matching answer, except that I use a "Last" parameter instead of the count.
-module(only_dupes).
-export([process/1]).
process([]) -> [];
process(L) when is_list(L) ->
[H|T] = lists:sort(L),
lists:sort(process(undefined, H, T, [])).
process(Last, Curr, [], Acc)
when Curr =/= Last ->
Acc;
process(_Last, Curr, [], Acc) ->
[Curr | Acc];
process(Last, Curr, [Next | Rest], Acc)
when Curr =/= Last, Curr =/= Next ->
process(Curr, Next, Rest, Acc);
process(_Last, Curr, [Next | Rest], Acc) ->
process(Curr, Next, Rest, [Curr | Acc]).
One way for iterating a list (that as a result will return a new list) is using recursion and pattern matching.
After you sort your list you want to iterate the list and to check not only that it is different from the next element, but that there was no other equal elements before it. Consider the list [3,3,3,5,5] if you will only check the next element, the last 3 will also be unique and that is incorrect.
Here is a working program, I used a counter to cover the above case as well. See the syntax for using [H|T] for iterating over the list. You may see more cases and read more about it here.
-module(test).
-export([remove_unique/1]).
remove_unique(Input) ->
Sorted = lists:sort(Input),
remove_unique(Sorted, [], 0).
% Base case - checks if element is unique
remove_unique([H|[]],Output,Count) ->
case Count of
0 -> Output;
_Other -> [H|Output]
end;
% Count is 0 - might be unique - check with next element
remove_unique([H1|[H2|T]],Output, 0)->
case (H1 =:= H2) of
true -> remove_unique([H2|T],[H1|Output],1);
false -> remove_unique([H2|T],Output,0)
end;
% Count is > 0 - not unique - proceed adding to list until next value
remove_unique([H1|[H2|T]],Output,Count) ->
case (H1 =:= H2) of
true -> remove_unique([H2|T],[H1|Output],Count+1);
false -> remove_unique([H2|T],[H1|Output],0)
end.
Test
7> test:remove_unique([1,2,3,3,3,5,5,6,7,7]).
[7,7,5,5,3,3,3]
8> test:remove_unique([1,2,3,3,3,5,5,6,7,8]).
[5,5,3,3,3]

test with loop in erlang

I have a list of values ​​ "Z0010", "Z0011", "Z0012", "Z0013" "Z0014", "Z0015", "Z0016", "Z0017", "Z0018", "Z0019"
I want to develop a function that takes a value in parameter
and I want to do a test in my function if the value passed as a parameter is equal to a value in the list in this cases it will show "existe" if not it displays "not existe"
I try with :
test(Token)->
case get_user_formid_by_token(Token) of
{ok, H} ->
FormId=string:substr(H, 2, length(H)),
Form=string:to_integer(FormId),
case verify (0019,1,Form) of
{ok}->io:format("existe");
{notok}->io:format("not existe")
end;
{error, notfound}-> io:format("qq")
end.
verify(VariableLength,VariableIncrement,FormId)->
lists:map(fun(I) -> if I =:= FormId ->
{ok};
I =/= FormId ->
{notok}
end
end,
lists:seq(0010, VariableLength, VariableIncrement)).
but when I execute this code it displays :
1> model:test("21137900").
** exception error: no case clause matching [{notok},
{notok},
{notok},
{notok},
{notok},
{notok},
{notok},
{notok},
{notok},
{notok}]
in function model:test/1
I try now with this solution :
get_user_formid_by_token(Token) ->
Q = qlc:q([{X#person.formid} || X <- mnesia:table(person),
X#person.token =:= Token]),
case do(Q) of
[{H}] ->
{ok, H};
[] ->
{error, notfound}
end.
test(Token)->
case get_user_formid_by_token(Token) of
{ok, H} ->
io:format("~s~n",[H]),
FormId=string:substr(H, 5, length(H)),
io:format("~s~n",[FormId]),
Form=string:to_integer(FormId),
io:format("~p~n",[Form]),
lists:member(Form, lists:seq(313, 320, 1));
{error, notfound}-> io:format("qq")
end.
but when I test I have this message in the console:
1> model:test("21137900").
Z000313
313
{313,[]}
false
the result should be true and not false
I think that Form=string:to_integer(FormId), it not return in this case 313
and another thing I want to add in my code
for example if H equal "Z000010" FormId=string:substr(H, 2, length(H)),
it return "000010"
Now I want to eliminate the first zero before the first integer not null so extarct 0000
before 1
lists:map/2 takes one list and creates a new list with the same number of values, so your list of 10 values is transformed into a list of 10 {ok} or {notok} tuples.
You probably want lists:member/2 instead.
5> lists:member(0, lists:seq(1, 3, 1)).
false
6> lists:member(3, lists:seq(1, 3, 1)).
true
7> lists:map(fun(X) -> ok end, lists:seq(1, 3, 1)).
[ok,ok,ok]
Have a look at the documentation (http://www.erlang.org/doc/man/string.html#to_integer-1):
to_integer(String) -> {Int, Rest} | {error, Reason}
Types:
String = string()
Int = integer()
Rest = string()
Reason = no_integer | not_a_list
So to_integer returns a tuple containing the number that was consumed from the string and the rest of the string. You can even tell from your test output where it says {313,[]}. In order to get the value of the number bound to your Formvariable, you need to decompose the tuple, which is typically done by pattern matching:
{Form,_Rest}=string:to_integer(FormId)
Now your Form will contain only the number 313.
The string:to_integerfunction will also happily eat the leading zeroes:
1> {Form, _} = string:to_integer("000010"), Form.
10

Resources