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 .
source share