Erlang Quoting through a list (or set) for processing files

I want to create 16 directories in Erlang. for (create_dir ("work / p" ++ A, where A is the item in the list [0, 1, ... f]) (sixteen is a number in hexadecimal notation).

Of course, I could write sixteen lines, such as: mkdir ("work / p0"), mkdir ("work / p1"), etc.

I looked at the lists: foreach. The examples use fun fun, can you define a function outside the loop and call it?

I am new to Erlang and am used to C ++ etc.

+4
source share
1 answer

Yes, it is possible to define a function (named) outside of lists:foreach/2 . Why do you want? This is the case when an anonymous function is incredibly convenient:

 lists:foreach(fun(N) -> file:make_dir( filename:join("work", "p"++integer_to_list(N, 16))) end, lists:seq(0, 15)). 

In the call to filename:join/2 , the appropriate directory separator will be used to construct the string work/pN , where N is an integer in the hexadecimal representation constructed using integer_to_list/2 , which converts the integer into a string (list) in (16).

lists:seq/2 is a friendly little function that returns the list [A,A+1,A+2,...,B-1,B] specified by A and B

Note that you could just use the list comprehension syntax, but since we are applying the functions to the list for side-effects, I decided to stick with foreach .

If you really want to define a separate function - call it foo and assume that it takes 42 arguments - you can refer to it as fun foo/42 in your code. This expression evaluates a function object, which, as an anonymous function defined in a string, can be passed to lists:foreach/2 .

+5
source

All Articles