ERlang - Trying to find LENGTH of constituents of List - erlang

guess its getting late, and Im a beginner, just need a little help..
Im trying to find the length of a list.. BUT NOT of the lists themselves, rather the length of the values within..
I take something like:
Other = [<<"366">>,0,
<<1>>,
<<"344">>,<<"Really"
<<1>>,
<<"989">>,<<"NotReally">>
<<1>>,
<<"345">>,4,
<<1>>,
<<"155">>,"209.191"]
I would really want to first convert Other into its RAW constituent binary
Example:
Other = [<<3>>,<<4>>,<<7>>,<<56>>,<<45>>,<<56>>...]
This, of course, is an example of way the original Other would look like(Not right conversion values). So that all of the values in there are there most basic binary data.
Then I could simply iterate through counting each <<_>> and determining the total message length.
Hope I was clear enough to find a solution.
Thanks all for the help, GN

iolist_size/1 is what you are looking for.
1> iolist_size([<<"366">>,0,<<1>>,<<"344">>,<<"Really">>,<<1>>,<<"989">>,<<"NotReally">>,<<1>>,<<"345">>,4,<<1>>,<<"155">>,"209.191"]).
43
2> v(1) - 1.
42
P.S.: Why your example data have this one surplus character? ;-)

If all you're trying to do is find the length of the entire structure, I'd try something like this:
my_length(X) when is_integer(X) -> 1;
my_length(X) when is_binary(X) -> erlang:size(X);
my_length(Lst) when is_list(Lst) ->
lists:sum([my_length(X) || X <- Lst]).
If you really want to build a flat version of your structure, then erlang:list_to_binary gets you pretty close to what you need, then just call size on that. (Actually, this may be better than my first attempt.)
1> erlang:list_to_binary([<<"366">>,0,<<"155">>,"209.191"]).
<<51,54,54,0,49,53,53,50,48,57,46,49,57,49>>

Related

Erlang: using io_lib to convert float to string [duplicate]

I am using a function to create a list from a float.
float_to_list(0.02).
It returns:
"2.00000000000000000000e-002"
I need it to give me a number exactly like:
"0.20"
If I fed it 5.23
"5.23"
If I fed it 5.5
"5.50"
So basically the number rounded to two decimal places.
Probably an easy fix.
Thanks
EDIT:
I would like to use the io format it looks like it might work,
but it dosen't in this example:
wxTextCtrl:setValue( TcGrossProfit, io:format("~p", [NUMBER]), ),
seems textctrl wants a string, I don't want to print it to the screen.
Are you looking for something like this:
6> F = 5/2.
2.50000
7> io_lib:format("~.1f",[F]).
["2.5"]
8> io_lib:format("~.2f",[F]).
["2.50"]
9> io_lib:format("~.3f",[F]).
["2.500"]
If yes, have a look at the io_lib module.
mochinum:digits converts a float to a string with an appropriate level of precision.
1> mochinum:digits(1.1).
"1.1"
2> mochinum:digits(1.2345).
"1.2345"
Not exactly what the OP requested, but useful nonetheless.
Alternatively you could use the function you were already using.
float_to_list(0.02,[{decimals, 2}]) outputs '0.02'
Or for Elixir users ;)
:erlang.float_to_list(5.231,[{:decimals, 2}]) outputs '5.2'
This link provides functions that truncate/floor or ceil or round a float. Given those you can round to 2 digits by multiplying by 100, rounging and then dividing back by 100 (and possibly rounding again to avoid precision errors)
I know people don't like the, "I am not an expert in language X" answers, but the printf command is quite ubiquitous so I will say, look for an analog of printf in Erlang.
Edit: It looks like the format and fwrite may be those analogs. For more info from erlang.org.

How to output text from lists of variable sizes using printf?

I'm trying to automate some output using printf but I'm struggling to find a way to pass to it the list of arguments expr_1, ..., expr_n in
printf (dest, string, expr_1, ..., expr_n)
I thought of using something like Javascript's spread operator but I'm not even sure I should need it.
For instace, say I have a list of strings to be output
a:["foo","bar","foobar"];
a string of appropriate format descriptors, say
s: "~a ~a ~a ~%";
and an output stream, say os. How can I invoke printf using these things in such a way that the result will be the same as writing
printf(os,s,a[1],a[2],a[3]);
Then I could generalize it to output lists of variable size.
Any suggestions?
Thanks.
EDIT:
I just learned about apply and, using the conditions I posed in my OP, the following seems to work wonderfully:
apply(printf,append([os,s],a));
Maxima printf implements most or maybe all of the formatting operators from Common Lisp FORMAT, which are quite extensive; see: http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm See also ? printf in Maxima to get an abbreviated list of formatting operators.
In particular for a list you can do something like:
printf (os, "my list: ~{~a~^, ~}~%", a);
to get the elements of a separated by ,. Here "~{...~}" tells printf to expect a list, and ~a is how to format each element, ~^ means omit the inter-element stuff after the last element, and , means put that between elements. Of course , could be anything.
There are many variations on that; if that's not what you're looking for, maybe I can help you find it.

Ruby:-Find the occurrences of a character in a file

I am looking for the Ruby method that can help me find the occurrences of a character in a file.I am looking for all occurrences, not just the first one.
I am able to read the file with the help of File.read("filename").
I do know how to find the no of occurrence in a particular string but dont know how to implement it when finding the characters in the file.
Please help.
Using File.read("filename") is not the most efficient way to do it, but it does not matter unless the file is too big, and if you are using it anyway, then File.read("filename") is indeed a string, so do it as you would with other strings.
File.read("filename").count(some_character)
or
File.new("filename").each_char.inject(0){|n, c| n += 1 if c == some_character; n}

How to write an array into a text file in maxima?

I am relatively new to maxima. I want to know how to write an array into a text file using maxima.
I know it's late in the game for the original post, but I'll leave this here in case someone finds it in a search.
Let A be a Lisp array, Maxima array, matrix, list, or nested list. Then:
write_data (A, "some_file.data");
Let S be an ouput stream (created by openw or opena). Then:
write_data (A, S);
Entering ?? numericalio at the input prompt, or ?? write_ or ?? read_, will show some info about this function and related ones.
I've never used maxima (or even heard of it), but a little Google searching out of curiousity turned up this: http://arachnoid.com/maxima/files_functions.html
From what I can gather, you should be able to do something like this:
stringout("my_new_file.txt",values);
It says the second parameter to the stringout function can be one or more of these:
input: all user entries since the beginning of the session.
values: all user variable and array assignments.
functions: all user-defined functions (including functions defined within any loaded packages).
all: all of the above. Such a list is normally useful only for editing and extraction of useful sections.
So by passing values it should save your array assignments to file.
A bit more necroposting, as google leads here, but I haven't found it useful enough. I've needed to export it as following:
-0.8000,-0.8000,-0.2422,-0.242
-0.7942,-0.7942,-0.2387,-0.239
-0.7776,-0.7776,-0.2285,-0.228
-0.7514,-0.7514,-0.2124,-0.212
-0.7168,-0.7168,-0.1912,-0.191
-0.6750,-0.6750,-0.1655,-0.166
-0.6272,-0.6272,-0.1362,-0.136
-0.5746,-0.5746,-0.1039,-0.104
So I've found how to do this with printf:
with_stdout(filename, for i:1 thru length(z_points) do
printf (true,"~,4f,~,4f,~,4f,~,3f~%",bot_points[i],bot_points[i],top_points[i],top_points[i]));
A bit cleaner variation on the #ProdoElmit's answer:
list : [1,2,3,4,5]$
with_stdout("file.txt", apply(print, list))$
/* 1 2 3 4 5 is then what appears in file.txt */
Here the trick with apply is needed as you probably don't want to have square brackets in your output, as is produced by print(list).
For a matrix to be printed out, I would have done the following:
m : matrix([1,2],[3,4])$
with_stdout("file.txt", for row in args(m) do apply(print, row))$
/* 1 2
3 4
is what you then have in file.txt */
Note that in my solution the values are separated with spaces and the format of your values is fixed to that provided by print. Another caveat is that there is a limit on the number of function parameters: for example, for me (GCL 2.6.12) my method does not work if length(list) > 64.

convert a string into another format

I would like to convert the binary string <<"abc">> into the following string "<a><b><c>" .
In other words, each byte shall be written between one "less than" char and one "greater than" char.
I suppose that the function is recursive ? Note that abc is just an example !
1>lists:flatten([[$<,C,$>]||C<-binary_to_list(<<"abc">>)]).
"<a><b><c>"
alternative
lists:flatmap(fun(C)-> [$<,C,$>] end,binary_to_list(<<"abc">>)).
or
f(C) -> [$<,C,$>].
lists:flatmap(fun f/1,binary_to_list(<<"abc">>)).
The most efficient if you want a flat list would probably be:
fr(<<C,Rest/binary>>) ->
[$<,C,$>|fr(Rest)];
fr(<<>>) -> [].
This expansion is similar to what a list/binary comprehension expands to.
Use a binary comprehension:
2> [[$<, C, $>] || <<C:1/binary>> <= <<"abc">>].
[[60,<<"a">>,62],[60,<<"b">>,62],[60,<<"c">>,62]]
So you don't have to process the binary into a list first and then work on it. It is probably a bit faster, especially for large lists, so if performance matter to you, it may be a viable alternative option.
this answer is probably not best one in terms of efficiency(i didn't compare it to other solutions) but it certainly helps to understand how you can invent your own iterators over different collections in erlang aimed for achieving your specific goal instead of using predefined iterators
fr(<<>>, Output) -> Output;
fr(<<"b", Rest/binary>>, Output) ->
fr(Rest, <<Output, "b">>);
fr(<<C:8, Rest/binary>>, Output) ->
fr(Rest, <<Output/binary, $<, C:8, $>>>).
f(Input) -> fr(Input, <<>>).
P.S. it looks like this solution is actually the most efficient :)

Resources