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.
Related
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.
Suppose in a (wx)Maxima session I have the following
f:sin(x);
df:diff(f,x);
Now I want to have it output a text file containing something like, for example
If $f(x)=\sin(x)$, then $f^\prime(x)=\cos(x)$.
I found the tex and tex1 functions but I think I need some additional string processing to be able to do what I want.
Any help appreciated.
EDIT: Further clarifications.
Auto Multiple Choice is a software that helps you create and manage questionaires. To declare questions one may use LaTeX syntax. From AMC's documentation, a question looks like this:
\element{geographie}{
\begin{question}{Cameroon}
Which is the capital city of Cameroon?
\begin{choices}
\correctchoice{Yaoundé}
\wrongchoice{Douala}
\wrongchoice{Abou-Dabi}
\end{choices}
\end{question}
}
As can be seen, it is just LaTeX. Now, with a little modification, I can turn this example into a math question
\element{derivatives}{
\begin{question}{trig_fun_diff_1}
If $f(x)=\sin(x)$ then $f^\prime(0)$ is
\begin{choices}
\correctchoice{$1$}
\wrongchoice{$-1$}
\wrongchoice{$0$}
\end{choices}
\end{question}
}
This is the sort of output I want. I'll have, say, a list of functions then execute a loop calculating their derivatives and so on.
OK, in response to your updated question. My advice is to work with questions and answers as expressions -- build up your list of questions first, and then when you have the list in the structure that you want, then output the TeX file as the last step. It is generally much clearer and simpler to work with expressions than with strings.
E.g. Here is a simplistic approach. I'll use defstruct to define a structure so that I can refer to its parts by name.
defstruct (question (name, datum, item, correct, incorrect));
myq1 : new (question);
myq1#name : "trig_fun_diff_1";
myq1#datum : f(x) = sin(x);
myq1#item : 'at ('diff (f(x), x), x = 0);
myq1#correct : 1;
myq1#incorrect : [0, -1];
You can also write
myq1 : question ("trig_fun_diff_1", f(x) = sin(x),
'at ('diff (f(x), x), x = 0), 1, [0, -1]);
I don't know which form is more convenient for you.
Then you can make an output function similar to this:
tex_question (q, output_stream) :=
(printf (output_stream, "\\begin{question}{~a}~%", q#name),
printf (output_stream, "If $~a$, then $~a$ is:~%", tex1 (q#datum), tex1 (q#item)),
printf (output_stream, "\\begin{choices}~%"),
/* make a list comprising correct and incorrect here */
/* shuffle the list (see random_permutation) */
/* output each correct or incorrect here */
printf (output_stream, "\\end{choices}~%"),
printf (output_stream, "\\end{question}~%));
where output_stream is an output stream as returned by openw (which see).
It may take a little bit of trying different stuff to get derivatives to be output in just the format you want. My advice is to put the logic for that into the output function.
A side effect of working with expressions is that it is straightforward to output some representations other than TeX (e.g. plain text, XML, HTML). That might or might not become important for your project.
Well, tex is the TeX output function. It can be customized to some extent via texput (which see).
As to post-processing via string manipulation, I don't recommend it. However, if you want to go down that road, there are regex functions which you can access via load(sregex). Unfortunately it's not yet documented; see the comment header of sregex.lisp (somewhere in your Maxima installation) for examples.
4> abs(1).
1
5> X = abs.
abs
6> X(1).
** exception error: bad function abs
7> erlang:X(1).
1
8>
Is there any particular reason why I have to use the module name when I invoke a function with a variable? This isn't going to work for me because, well, for one thing it is just way too much syntactic garbage and makes my eyes bleed. For another thing, I plan on invoking functions out of a list, something like (off the top of my head):
[X(1) || X <- [abs, f1, f2, f3...]].
Attempting to tack on various module names here is going to make the verbosity go through the roof, when the whole point of what I am doing is to reduce verbosity.
EDIT: Look here: http://www.erlangpatterns.org/chain.html The guy has made some pipe-forward function. He is invoking functions the same way I want to above, but his code doesn't work when I try to use it. But from what I know, the guy is an experienced Erlang programmer - I saw him give some keynote or whatever at a conference (well I saw it online).
Did this kind of thing used to work but not anymore? Surely there is a way I can do what I want - invoke these functions without all the verbosity and boilerplate.
EDIT: If I am reading the documentation right, it seems to imply that my example at the top should work (section 8.6) http://erlang.org/doc/reference_manual/expressions.html
I know abs is an atom, not a function. [...] Why does it work when the module name is used?
The documentation explains that (slightly reorganized):
ExprM:ExprF(Expr1,...,ExprN)
each of ExprM and ExprF must be an atom or an expression that
evaluates to an atom. The function is said to be called by using the
fully qualified function name.
ExprF(Expr1,...,ExprN)
ExprF
must be an atom or evaluate to a fun.
If ExprF is an atom the function is said to be called by using the implicitly qualified function name.
When using fully qualified function names, Erlang expects atoms or expression that evaluates to atoms. In other words, you have to bind X to an atom: X = atom. That's exactly what you provide.
But in the second form, Erlang expects either an atom or an expression that evaluates to a function. Notice that last word. In other words, if you do not use fully qualified function name, you have to bind X to a function: X = fun module:function/arity.
In the expression X=abs, abs is not a function but an atom. If you want thus to define a function,you can do so:
D = fun erlang:abs/1.
or so:
X = fun(X)->abs(X) end.
Try:
X = fun(Number) -> abs(Number) end.
Updated:
After looking at the discussion more, it seems like you're wanting to apply multiple functions to some input.
There are two projects that I haven't used personally, but I've starred on Github that may be what you're looking for.
Both of these projects use parse transforms:
fun_chain https://github.com/sasa1977/fun_chain
pipeline https://github.com/stolen/pipeline
Pipeline is unique because it uses a special syntax:
Result = [fun1, mod2:fun2, fun3] (Arg1, Arg2).
Of course, it could also be possible to write your own function to do this using a list of {module, function} tuples and applying the function to the previous output until you get the result.
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 :)
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>>