Erlang gives syntax error on record construction - syntax

I have the following code in a module:
-module(my_server).
-record(server_opts,
{port, ip = "127.0.0.1", max_connections = 10}).
Opts1 = #server_opts{port=80}.
When I try to compile it in Erlang shell it gives an error like
syntax error before Opts1. Any idea what could be the problem with the code above. Please note that the code is taken from the following website:
Record example in Erlang.

The following line:
Opts1 = #server_opts{port=80}.
Should be contained within a function body:
foo() ->
Opts1 = #server_opts{port=80},
...
Remember to export the function, so that you can call it from outside the module:
-export([test_records/0]).
A complete example follows:
-module(my_server).
-export([test_records/0]).
-record(server_opts, {port,
ip = "127.0.0.1",
max_connections = 10}).
test_records() ->
Opts1 = #server_opts{port=80},
Opts1#server_opts.port.

Maybe, you've thought that Opts1 is a global constant, but there are no global variables in erlang.
You may use macro definitions to have something like global constants (which are actually replaced in compile time):
-module(my_server).
-record(server_opts,
{port,
ip="127.0.0.1",
max_connections=10}).
%% macro definition:
-define(Opts1, #server_opts{port=80}).
%% and use it anywhere in your code:
my_func() ->
io:format("~p~n",[?Opts1]).
P.S.
Using records from shell. Assume - you've created file my_server.hrl which contain definition of record server_opts. First of all you're have to load record definition, using function rr("name_of_file_with_record_definition"), after this you're ready to work with records in shell:
1> rr("my_record.hrl").
[server_opts]
2>
2> Opts1 = #server_opts{port=80}.
#server_opts{port = 80,ip = "127.0.0.1",
max_connections = 10}
3>
3> Opts1.
#server_opts{port = 80,ip = "127.0.0.1",
max_connections = 10}
4>

Related

How to debug with PureScript?

Issue
Following is a minimal, contrived example:
read :: FilePath -> Aff String
read f = do
log ("File: " <> f) -- (1)
readTextFile UTF8 f -- (2)
I would like to do some debug logging in (1), before a potential error on (2) occurs. Executing following code in Spago REPL works for success cases so far:
$ spago repl
> launchAff_ $ read "test/data/tree/root.txt"
File: test/data/tree/root.txt
unit
Problem: If there is an error with (2) - file is directory here - , (1) seems to be not executed at all:
$ spago repl
> launchAff_ $ read "test/data/tree"
~/purescript-book/exercises/chapter9/.psci_modules/node_modules/Effect.Aff/foreign.js:532
throw util.fromLeft(step);
^
[Error: EISDIR: illegal operation on a directory, read] {
errno: -21,
code: 'EISDIR',
syscall: 'read'
}
The original problem is more complex including several layers of recursions (see E-Book exercise 3), where I need logging to debug above error.
Questions
How can I properly log regardless upcoming errors here?
(Optional) Is there a more sophisticated, well-established debugging alternative - purescript-debugger? A decicated VS Code debug extension/functionality would be the cherry on the cake.
First of all, the symptoms you observe do not mean that the first line doesn't execute. It does always execute, you're just not seeing output from it due to how console works in the PureScript REPL. The output gets swallowed. Not the only problem with REPL, sadly.
You can verify that the first line is always executed by replacing log with throwError and observing that the error always gets thrown. Or, alternatively, you can make the first line modify a mutable cell instead of writing to the console, and then examine the cell's contents.
Finally, this only happens in REPL. If you put that launchAff_ call inside main and run the program, you will always get the console output.
Now to the actual question at hand: how to debug trace.
Logging to console is fine if you can afford it, but there is a more elegant way: Debug.trace.
This function has a hidden effect - i.e. its type says it's pure, but it really produces an effect when called. This little lie lets you use trace in a pure setting and thus debug pure code. No need for Effect! This is ok as long as used for debugging only, but don't put it in production code.
The way it works is that it takes two parameters: the first one gets printed to console and the second one is a function to be called after printing, and the result of the whole thing is whatever that function returns. For example:
calculateSomething :: Int -> Int -> Int
calculateSomething x y =
trace ("x = " <> show x) \_ ->
x + y
main :: Effect Unit
main =
log $ show $ calculateSomething 37 5
> npx spago run
'x = 37'
42
The first parameter can be anything at all, not just a string. This lets you easily print a lot of stuff:
calculateSomething :: Int -> Int -> Int
calculateSomething x y =
trace { x, y } \_ ->
x + y
> npx spago run
{ x: 37, y: 5 }
42
Or, applying this to your code:
read :: FilePath -> Aff String
read f = trace ("File: " <> f) \_ -> do
readTextFile UTF8 f
But here's a subtle detail: this tracing happens as soon as you call read, even if the resulting Aff will never be actually executed. If you need tracing to happen on effectful execution, you'll need to make the trace call part of the action, and be careful not to make it the very first action in the sequence:
read :: FilePath -> Aff String
read f = do
pure unit
trace ("File: " <> f) \_ -> pure unit
readTextFile UTF8 f
It is, of course, a bit inconvenient to do this every time you need to trace in an effectful context, so there is a special function that does it for you - it's called traceM:
read :: FilePath -> Aff String
read f = do
traceM ("File: " <> f)
readTextFile UTF8 f
If you look at its source code, you'll see that it does exactly what I did in the example above.
The sad part is that trace won't help you in REPL when an exception happens, because it's still printing to console, so it'll still get swallowed for the same reasons.
But even when it doesn't get swallowed, the output is a bit garbled, because trace actually outputs in color (to help you make it out among other output), and PureScript REPL has a complicated relationship with color:
> calculateSomething 37 5
←[32m'x = 37'←[39m
42
In addition to Fyodor Soikin's great answer, I found a variant using VS Code debug view.
1.) Make sure to build with sourcemaps:
spago build --purs-args "-g sourcemaps"
2.) Add debug configuration to VS Code launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"runtimeArgs": ["-e", "require('./output/Main/index.js').main()"],
"smartStep": true // skips files without (valid) source map
}
]
}
Replace "./output/Main/index.js" / .main() with the compiled .js file / function to be debugged.
3.) Set break points and step through the .purs file via sourcemap support.

Error with Condor: "$INT() macro: 50+ $((0/41)) does not evaluate to an integer!"

I want to run several jobs with Condor, my executable take as an argument b such that: b1=50+ $(($(Process)/41)), where $(())stands for the quotient of $(Process) divided by 41. b is defined in quotient.sh. Here is my submit file:
# Unix submit description file
include : PATH/quotient.sh
executable = PATH/script_test.sh
arguments = $(b) $(Process)
log = fit_it_data_$INT(b)_$(Process).log
output = outfile_fit_$INT(b)_$(Process).txt
error = errors_fit_$INT(b)_$(Process).txt
transfer_input_files = PATH
should_transfer_files = Yes
when_to_transfer_output = ON_EXIT
queue 81
However I am getting the error Submitting job(s)ERROR at Queue statement on Line 13: $INT() macro: 50+ $((0/41)) does not evaluate to an integer!. I don't understand why it complains that is does not evaluate to an integer, since b should be equal to 50 here...
Any idea how to fix that issue?
b1=50+ $(($(Process)/41))
I think you have an extra "$" in there. Try this:
b1=50+ ($(Process)/41)

How to access JSON from external data source in Terraform?

I am receiving JSON from a http terraform data source
data "http" "example" {
url = "${var.cloudwatch_endpoint}/api/v0/components"
# Optional request headers
request_headers {
"Accept" = "application/json"
"X-Api-Key" = "${var.api_key}"
}
}
It outputs the following.
http = [{"componentID":"k8QEbeuHdDnU","name":"Jenkins","description":"","status":"Partial Outage","order":1553796836},{"componentID":"ui","name":"ui","description":"","status":"Operational","order":1554483781},{"componentID":"auth","name":"auth","description":"","status":"Operational","order":1554483781},{"componentID":"elig","name":"elig","description":"","status":"Operational","order":1554483781},{"componentID":"kong","name":"kong","description":"","status":"Operational","order":1554483781}]
which is a string in terraform. In order to convert this string into JSON I pass it to an external data source which is a simple ruby function. Here is the terraform to pass it.
data "external" "component_ids" {
program = ["ruby", "./fetchComponent.rb",]
query = {
data = "${data.http.example.body}"
}
}
Here is the ruby function
#!/usr/bin/env ruby
require 'json'
data = JSON.parse(STDIN.read)
results = data.to_json
STDOUT.write results
All of this works. The external data outputs the following (It appears the same as the http output) but according to terraform docs this should be a map
external1 = {
data = [{"componentID":"k8QEbeuHdDnU","name":"Jenkins","description":"","status":"Partial Outage","order":1553796836},{"componentID":"ui","name":"ui","description":"","status":"Operational","order":1554483781},{"componentID":"auth","name":"auth","description":"","status":"Operational","order":1554483781},{"componentID":"elig","name":"elig","description":"","status":"Operational","order":1554483781},{"componentID":"kong","name":"kong","description":"","status":"Operational","order":1554483781}]
}
I was expecting that I could now access data inside of the external data source. I am unable.
Ultimately what I want to do is create a list of the componentID variables which are located within the external data source.
Some things I have tried
* output.external: key "0" does not exist in map data.external.component_ids.result in:
${data.external.component_ids.result[0]}
* output.external: At column 3, line 1: element: argument 1 should be type list, got type string in:
${element(data.external.component_ids.result["componentID"],0)}
* output.external: key "componentID" does not exist in map data.external.component_ids.result in:
${data.external.component_ids.result["componentID"]}
ternal: lookup: lookup failed to find 'componentID' in:
${lookup(data.external.component_ids.*.result[0], "componentID")}
I appreciate the help.
can't test with the variable cloudwatch_endpoint, so I have to think about the solution.
Terraform can't decode json directly before 0.11.x. But there is a workaround to work on nested lists.
Your ruby need be adjusted to make output as variable http below, then you should be fine to get what you need.
$ cat main.tf
variable "http" {
type = "list"
default = [{componentID = "k8QEbeuHdDnU", name = "Jenkins"}]
}
output "http" {
value = "${lookup(var.http[0], "componentID")}"
}
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
http = k8QEbeuHdDnU

How can I use erl_lint to syntax check an Erlang module?

I'm trying to use erl_lint() to build a simple Erlang syntax and style checker. I've gotten far enough to load the file and parse it into Forms and to get erl_lint to partially understand it, but then erl_lint complains about undefined functions that are defined. What am I doing wrong?
erlint.erl :
-module(erlint).
-export([lint/1]).
% based on http://stackoverflow.com/a/28086396/13675
lint(File) ->
{ok, B} = file:read_file(File),
Forms = scan(erl_scan:tokens([],binary_to_list(B),1),[]),
F = fun(X) -> {ok,Y} = erl_parse:parse_form(X), Y end,
erl_lint:module([F(X) || X <- Forms],File).
scan({done,{ok,T,N},S},Res) ->
scan(erl_scan:tokens([],S,N),[T|Res]);
scan(_,Res) ->
lists:reverse(Res).
hello.erl :
-module(hello).
-export([hello_world/0]).
hello_world() -> io:fwrite("hello, world\n").
attempt to use :
1> c(erlint).
{ok,erlint}
2> erlint:lint("hello.erl").
{error,[{"hello.erl",
[{2,erl_lint,{undefined_function,{hello_world,0}}}]}],
[]}
I'm not sure this approach fits with your overall plan, but you could instead compile the input file, extract its abstract forms from the resulting beam, and pass them to erl_lint:
-module(erlint).
-export([lint/1]).
lint(File) ->
{ok,_,Bin} = compile:file(File,[debug_info,binary]),
{ok,{_,[{abstract_code,{_,AC}}]}} = beam_lib:chunks(Bin,[abstract_code]),
erl_lint:module(AC,File).
Let's change your hello.erl to include an unused variable:
-module(hello).
-export([hello_world/0]).
hello_world() ->
X = io:fwrite("hello, world\n").
We see that this version of erlint:lint/1 correctly reports it:
1> erlint:lint("hello.erl").
{ok,[{"hello.erl",[{5,erl_lint,{unused_var,'X'}}]}]}
If you need them for your overall purposes, note that you can retrieve source code forms from the abstract forms variable AC by calling erl_syntax:form_list(AC).

Why cannot do I get syntax errors when trying to define functions in Erlang?

I am try to learn Erlang. I've installed a runtime but cannot get it working. The following code:
X = 3.
works, but none of the following statements work:
f(X)->X.
F() ->0.
F([])->[].
I get back 1: syntax error before: '->'. I tried the word_count from this tutorial. And I get the same error.
What is wrong here?
In REPL you have to use fun(...) -> ... end:
1> F = fun(X) -> X end.
#Fun<erl_eval.6.80484245>
2> F(42).
42
If you have code in file use c command:
1> c(word_count).
{ok,word_count}
2> word_count:word_count([]).
0
There is difference in sytax when writing functions in Erlang module and Erlang shell (REPL). As P_A mentioned you need to call as F = fun(X) -> X end, F("Echo").
Also note that function names are atoms so has to start with lowercase when you are writing in Erlang module. If you are serious about learning Erlang I would suggest you go through this.
You mentioned that you worked on F#. The basic difference between F# and Erlang in this case is that expression
let Lilo = [|5; 3; -3; 0; 0.5|];; Can be written directly in the file and executed. In Erlang it can only be done in Erlang shell and not inside a file.
So the expression you are trying should be inside a function inside a module with the same name as file. Consider test.erl file. Any function you export can be called from outside (shell).
-module(test).
-export([test/0]).
test() ->
Lilo = [5, 3, -3, 0, 0.5],
[X*2 || X <-Lilo].

Resources