'Is there any special syntax for shell to editor for erlang?
I am new to erlang, I have been learning to code on console/command prompt. Now I have to do the below code on editor. I need the sum of given numbers (a list [1,2,3]) with foldl/3 function.
lists:foldl(fun(X, Sum) -> X + Sum end,0,[1,2,3]).
-module(test).
-export([function1/1]).
function1(L) ->
L = [1,2,3],
lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
Pardon me for the wrong format, Please let me know the correct way to do the same thing on the editor.
Thanks in advance
Solution 1:[1]
I have been learning to code on console/command prompt.
That's not very smart, but if you like the tedium of typing stuff into the shell, have at it. If you type your code in a file, using an erlang code editor that automatically does the indenting, then compile your file, you can easily edit the file to make changes, then recompile.
Now I have to do the below code on editor.
function1(L) -> L = [1,2,3], lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
First, there's an obvious error in that code, namely you can only assign to a variable once. If you call that function with one argument, then the parameter variable L will be assigned the argument. Yet, on the very next line, the code tries to assign to L again. Error!
Second, you can't define a named function in the shell, however you can do almost the same thing: create an anonymous function and assign it to a variable. Here's an example:
1> F1 = fun(Data) ->
1> lists:foldl(fun(X, Sum) -> X + Sum end, 0, Data)
1> end.
#Fun<erl_eval.44.40011524>
2> F1([1, 2, 3]).
6
=========
After rereading your post, it sounds like you want to convert this line in the console:
lists:foldl(fun(X, Sum) -> X + Sum end,0,[1,2,3])
into a function defined in a file. The function should take one argument, where the argument is a list of numbers that should be summed up using lists:foldl/3. Is that correct? If so, here's an example:
Put this code in a file named
a.erlin some directory:-module(a). -export([f1/1]). f1(List) -> lists:foldl( fun(X, Sum) -> X + Sum end, 0, List ).Note that the module name and the file name have to match.
In a terminal window, switch directories to the directory containing that file, e.g.
$ cd erlang_programsThen do this:
~/erlang_programs$ erl Erlang/OTP 24 [erts-12.0.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] Eshell V12.0.2 (abort with ^G) 1> c(a). <--Compiles the file named a.erl in the current directory. {ok,a} <--- Or, you may get a listing of errors which must be corrected to compile the file. 2> a:f1([1, 2, 3]). 6 3> a:f1([10, 20, 30]). 60You have to call the function using the syntax
module:function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
