Retrieve value by variable name in erlang function - erlang

Is it possible somehow to retrieve variable value by its name (name represented as string)?
% we are calling foo function as foo(3)
foo(Param) ->
Var1 = Param * 2,
% some magic code here which can evaluate
% "Var1" string to Var1's value (6)
ok.
I want to implement (if it is possible) some kind of logger macro, like
Param = 3*4,
% This should write "My parameter value is 12" to log
?LOG("My parameter value is $Param").
Thanks.

The common way to log is to have formatting string and list of parameters. However your idea is achievable through usage of parse transform.

Thanks to Dmitry Belyaev for mentioning parse transform.
Say we have logging code:
?dump("My parameter value is $Param")
What I need here is to parse variables within format string ("My parameter value is $Param") with some regular expression. This format string contains single var name (Param). And we need to insert io_lib:format function call (by transforming original AST) with modified format string:
print_message(io_lib:format("My parameter value is ~p~n", [Param]))
In result we can archive required behavior:
Bar = "hello",
Buzz = buzz123,
?dump("Say $Bar to $Buzz"),
% => example:19: Say "hello" to buzz123
You can look at my implementation here

For toy problems you could use:
io:format("My parameter value is ~p~n", [Param]).
See io_lib and io.
Alternatively:
error_logger:info_report/1
or other error_logger functions.
The logging library lager is commonly used.

Related

calculating string length causes confustion

I am confused by the following output:
local a = "string"
print(a.len) -- function: 0xc8a8f0
print(a.len(a)) -- 6
print(len(a))
--[[
/home/pi/test/wxlua/wxLua/ZeroBraneStudio/bin/linux/armhf/lua: /home/pi/Desktop/untitled.lua:4: attempt to call global 'len' (a nil value)
stack traceback:
/home/pi/Desktop/untitled.lua:4: in main chunk
[C]: ?
]]
What is the proper way to calculate a string length in Lua?
Thank you in advance,
You can use:
a = "string"
string.len(a)
Or:
a = "string"
a:len()
Or:
a = "string"
#a
EDIT: your original code is not idiomatic but is also working
> a = "string"
> a.len
function: 0000000065ba16e0
> a.len(a)
6
The string a is linked to a table (named metatable) containing all the methods, including len.
A method is just a function, taking the string as the first parameter.
function a.len (string) .... end
You can call this function, a.len("test") just like a normal function. Lua has a special syntax to make it easier to write. You can use this special syntax and write a:len(), it will be equivalent to a.len(a).
print(a.len) -- function: 0xc8a8f0
This prints a string representation of a.len which is a function value. All strings share a common metatable.
From Lua 5.4 Reference Manual: 6.4 String Manipulation:
The string library provides all its functions inside the table string.
It also sets a metatable for strings where the __index field points to
the string table. Therefore, you can use the string functions in
object-oriented style. For instance, string.byte(s,i) can be written
as s:byte(i).
So given that a is a string value, a.len actually refers to string.len
For the same reason
print(a.len(a))
is equivalent to print(string.len(a)) or print(a:len()). This time you called the function with argument a instead of printing its string representation so you print its return value which is the length of string a.
print(len(a))
on the other hand causes an error because you attempt to call a global nil value. len does not exist in your script. It has never been defined and is hence nil. Calling nil values doesn't make sense so Lua raises an error.
According to Lua 5.4 Reference Manual: 3.4.7 Length Operator
The length of a string is its number of bytes. (That is the usual
meaning of string length when each character is one byte.)
You can also call print(#a) to print a's length.
The length operator was introduced in Lua 5.1,

string.format variable number of arguments

Luas string.format is pretty straight forward, if you know what to format.
However, I stuck at writing a function which takes a wildcard-string to format, and a variable number of arguments to put into that blank string.
Example:
str = " %5s %3s %6s %6s",
val = {"ttyS1", "232", "9600", "230400"}
Formatting that by hand is pretty easy:
string.format( str, val[1], val[2], val[3], val[4] )
Which is the same as:
string.format(" %5s %3s %6s %6s", "ttyS1, "232", "9600","230400")
But what if I wan't to have a fifth or sixth argument?
For example:
string.format(" %1s %2s %3s %4s %5s %6s %7s %", ... )
How can I implement a string.format with an variable number of arguments?
I want to avoid appending the values one by one because of performance issues.
The application runs on embedded MCUs.
Generate arbitrary number of repeats of whatever format you want with string.rep if format is the same for all arguments. Or fill table with all formats and use table.concat. Remember that you don't need to specify index of argument in format if you don't want to reorder them.
If you just need to concatenate strings together separated by space, use more suitable tool: table.concat(table_of_strings, ' ').
You can create a table using varargs:
function foo(fmt, ...)
local t = {...}
return t[6] -- might be nil
end
Ps, don't use # on the table if you expect the argument list might contain nil. Instead use select("#", ...).

Type to represent a string which is not empty or spaces in F#

I love the simplicity of types like
type Code = Code of string
But I would like to put some restrictions on string (in this case - do not allow empty of spaces-only strings). Something like
type nonemptystring = ???
type Code = Code of nonemptystring
How do I define this type in F# idiomatic way? I know I can make it a class with constructor or a restricted module with factory function, but is there an easy way?
A string is essentially a sequence of char values (in Haskell, BTW, String is a type alias for [Char]). A more general question, then, would be if it's possible to statically declare a list as having a given size.
Such a language feature is know as Dependent Types, and F# doesn't have it. The short answer, therefore, is that this is not possible to do in a declarative fashion.
The easiest, and probably also most idiomatic, way, then, would be to define Code as a single-case Discriminated Union:
type Code = Code of string
In the module that defines Code, you'd also define a function that clients can use to create Code values:
let tryCreateCode candidate =
if System.String.IsNullOrWhiteSpace candidate
then None
else Some (Code candidate)
This function contains the run-time logic that prevents clients from creating empty Code values:
> tryCreateCode "foo";;
val it : Code option = Some (Code "foo")
> tryCreateCode "";;
val it : Code option = None
> tryCreateCode " ";;
val it : Code option = None
What prevents a client from creating an invalid Code value, then? For example, wouldn't a client be able to circumvent the tryCreateCode function and simply write Code ""?
This is where signature files come in. You create a signature file (.fsi), and in that declare types and functions like this:
type Code
val tryCreateCode : string -> Code option
Here, the Code type is declared, but its 'constructor' isn't. This means that you can't directly create values of this types. This, for example, doesn't compile:
Code ""
The error given is:
error FS0039: The value, constructor, namespace or type 'Code' is not defined
The only way to create a Code value is to use the tryCreateCode function.
As given here, you can no longer access the underlying string value of Code, unless you also provide a function for that:
let toString (Code x) = x
and declare it in the same .fsi file as above:
val toString : Code -> string
That may look like a lot of work, but is really only six lines of code, and three lines of type declaration (in the .fsi file).
Unfortunately there isn't convenient syntax for declaring a restricted subset of types but I would leverage active patterns to do this. As you rightly say, you can make a type and check it's validity when you construct it:
/// String type which can't be null or whitespace
type FullString (string) =
let string =
match (System.String.IsNullOrWhiteSpace string) with
|true -> invalidArg "string" "string cannot be null or whitespace"
|false -> string
member this.String = string
Now, constructing this type naively may throw runtime exceptions and we don't want that! So let's use active patterns:
let (|FullStr|WhitespaceStr|NullStr|) (str : string) =
match str with
|null -> NullStr
|str when System.String.IsNullOrWhiteSpace str -> WhitespaceStr
|str -> FullStr(FullString(str))
Now we have something that we can use with pattern matching syntax to build our FullStrings. This function is safe at runtime because we only create a FullString if we're in the valid case.
You can use it like this:
let printString str =
match str with
|NullStr -> printfn "The string is null"
|WhitespaceStr -> printfn "The string is whitespace"
|FullStr fstr -> printfn "The string is %s" (fstr.String)

Using Format in a livebindings CustomFormat

I'm trying to use LiveBindings to format a number for display in a TEdit on a FireMonkey form.
I'm trying to use the Format method in the CustomFormat of the binding to format the number with two decimal places.
I can 'hard code' the output:
Format("Hello", %s)
which is working, but I can't work out what formatting string to use. If I try a standard formatting string such as,
Format("%.2f", %s)
I get a runtime error "Format invalid or incompatible with argument".
Indeed I get an error whenever I include a % symbol in the format string, so I'm guessing Format takes a different type of argument, but I can't find any documentation to say what the correct format string is.
You can not use Format('%.2f',[%s]) in LiveBindings -> CustomFormat
The %s is reserved for the data and for a TEdit , it's a string
d : double;
s : string;
...
d := 1234.5678;
s:=Format('%.2f',[d]);
Format() is to convert [int, decimal, double, float] to a string .
all other give you a error : invalid argument
valid is for example
TLinkControlToField1 -> CustomFormat : "Double : "+UpperCase(%s)
will give you in Edit1.text
Double : 1234.5678
OK , we know that Uppercase() for '1234.5678' has no effects .
Is only to show (%s) is a string
Solutions:
Set to TFloatField -> DisplayFormat #00000.00
rounds and display 01234.57
check TFloatField -> currency
rounds and display 1234.57
use a component look here
LiveBindings in XE3: Formatting your Fields
The parameter is passed into CustomFormat as %s. The bindings system preparses out this parameter before the data is passed onto the evaluator. Thus any other % symbols in the CustomFormat string will give an error.
As with a normal format string you can include a literal % sign by putting a double % (i.e. %%).
So, any %s in the format string need to be converted to %%, e.g.
Format('%%.2f', %s)
which gets parsed out to
Format('%.2f', 67.66666)
and then parsed down to
67.67
for display.
If you want to include a literal % in the final output you need to put a quadrupal %, e.g.
Format('%%.2f%%%%', %s)
becomes
Format('%.2f%%', 67.6666)
and displays as
67.67%
Note: The normal format function takes a final parameter which is an array of values. The Format method in the bindings system takes a variable length list of parameters.
Also, the method names are case sensitive. 'Format' is correct, 'format' will fail.
imput 67.6666
CUSTOM FORMAT: ToStr(Format('%%.2f', Value)) + ' %%'
output 67.00 %

Erlang matchspecs with tuple comparison

I want to use erlang datetime values in the standard format {{Y,M,D},{H,Min,Sec}} in a MNESIA table for logging purposes and be able to select log entries by comparing with constant start and end time tuples.
It seems that the matchspec guard compiler somehow confuses tuple values with guard sub-expressions. Evaluating ets:match_spec_compile(MatchSpec) fails for
MatchSpec = [
{
{'_','$1','$2'}
,
[
{'==','$2',{1,2}}
]
,
['$_']
}
]
but succeeds when I compare $2 with any non-tuple value.
Is there a restriction that match guards cannot compare tuple values?
I believe the answer is to use double braces when using tuples (see Variables and Literals section of http://www.erlang.org/doc/apps/erts/match_spec.html#id69408). So to use a tuple in a matchspec expression, surround that tuple with braces, as in,
{'==','$2',{{1,2}}}
So, if I understand your example correctly, you would have
22> M=[{{'_','$1','$2'},[{'==','$2',{{1,2}}}],['$_']}].
[{{'_','$1','$2'},[{'==','$2',{{1,2}}}],['$_']}]
23> ets:match_spec_run([{1,1,{1,2}}],ets:match_spec_compile(M)).
[{1,1,{1,2}}]
24> ets:match_spec_run([{1,1,{2,2}}],ets:match_spec_compile(M)).
[]
EDIT: (sorry to edit your answer but this was the easiest way to get my comment in a readable form)
Yes, this is how it must be done. An easier way to get the match-spec is to use the (pseudo) function ets:fun2ms/1 which takes a literal fun as an argument and returns the match-spec. So
10> ets:fun2ms(fun ({A,B,C}=X) when C == {1,2} -> X end).
[{{'$1','$2','$3'},[{'==','$3',{{1,2}}}],['$_']}]
The shell recognises ets:fun2ms/1. For more information see ETS documentation. Mnesia uses the same match-specs as ETS.

Resources