If i call the test(), it doesnt work. Can someone explain this ?.
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(debug, [test1]).
test1 on its own is simply an atom, not a reference to the local function. To create a reference to the function use fun Function/Arity as below.
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(C, [fun test1/0]).
You could also construct an anonymous function that calls test1 like this: fun() -> test1() end, but there's no reason to that unless you have additional values you want to pass in or the like.
The other two answers do actually answer the question. I just want to add to them.
I expect that you want to be able to pass an atom and call the function with that name. This is not possible for local functions. It is very possible for exported functions though.
So you can do something like (my only change is to add "?MODULE:", and to change "debug" to "C"):
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = ?MODULE:F(), io:format("~p ", [Val]) end,
lists:foreach(C, [test1]).
First, C variable hasn't been used at all, and second you should wrap the test1 with a fun/end:
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(C, [fun() -> test1() end]).
Related
Is it possible to write a function that returns an anonymous function of a specified arity? I'd like to be able to generate a function that can be passed to meck:expect/3 as the third argument so I can dynamically mock existing functions of any arity?
I've done quite a bit of searching and it seems like the only way to solve this is by hardcoding things like this:
gen_fun(1, Function) ->
fun(A) -> Function([A]) end;
gen_fun(2, Function) ->
fun(A, B) -> Function([A, B]) end;
...
It's not pretty, but you can use the same trick as the shell and build your functions from the ground up:
-module(funny).
-export([gen_fun/1, gen_fun/2]).
-spec gen_fun(function()) -> function().
gen_fun(Function) ->
{arity, Arity} = erlang:fun_info(Function, arity),
gen_fun(Arity, Function).
-spec gen_fun(non_neg_integer(), function()) -> function().
gen_fun(Arity, Function) ->
Params = [{var, 1, list_to_atom([$X| integer_to_list(I)])} || I <- lists:seq(1, Arity)],
Anno = erl_anno:new(1),
Expr =
{'fun',
Anno,
{clauses, [{clause, Anno, Params, [], [{call, Anno, {var, Anno, 'Function'}, Params}]}]}},
{value, Fun, _Vars} = erl_eval:expr(Expr, [{'Function', Function}]),
Fun.
Then, in the shellβ¦
1> F = funny:gen_fun(fun io:format/2).
#Fun<erl_eval.43.40011524>
2> F("~ts~n", ["π"]).
π
ok
3> F1 = funny:gen_fun(fun io:format/1).
#Fun<erl_eval.44.40011524>
4> F1("π~n").
π
ok
5>
Is there a better way to implement Racket's ormap in Erlang than:
ormap(_, []) -> false;
ormap(Pred, [H|T]) ->
case Pred(H) of
false -> ormap(Pred, T);
_ -> {ok, Pred(H)}
end.
Looks pretty good to me. I'm not sure how smart Erlang is about optimizing these things, but you might want to actually bind the non-false pattern match to a variable, and avoid recomputing Pred(H).
ormap(_, []) -> false;
ormap(Pred, [H|T]) ->
case Pred(H) of
false -> ormap(Pred, T);
V -> {ok, V}
end.
The Racket version doesn't include the ok symbol, but that seems like the Erlangy thing to do so I don't see anything wrong with it. You might similarly expect Pred to return an attached ok symbol for the non-false case, in which case:
V -> V
or
{ok, V} -> {ok, V}
should work.
I want to write a function in F#, that exposes the following type signature to C#:
public static FSharpFunc<FSharpFunc<Unit,Unit>,Unit> foo(Action<Action> f)
In F# I tried writing:
let foo (f : Action<Action>) : ((unit -> unit) -> unit) = ...
But that produces the C# signature:
public static void foo(Action<Action> f, FSharpFunc<Unit,Unit> x)
The F# has treated my code equivalently to:
let foo (f : Action<Action>) (g : unit -> unit) : unit = ...
Of course, these are equivalent to F#, but very different in C#. Is there anything I can do to produce the C# I want? (F# 2.0.0.0)
As a quick hack, I rewrote my F# to:
let foo (f : Action<Action>) ((unit -> unit) -> unit)[] = ...
Then I just use Head in the C#.
If you write let foo x = fun () -> ... then the F# compiler optimizes the code and compiles it as a method that takes two arguments (instead of a method returning function which is what you need). To get a function value as the result, you need to "do something" before returning the function:
// Will be compiled as method taking Action, FastFunc and returning void
let foo1(x : Action<Action>) : (unit -> unit) -> unit =
fun f -> f ()
// Will be compiled as method taking Action and returning FastFunc of FastFunc
let foo2(x : Action<Action>) : ((unit -> unit) -> unit) =
ignore ();
fun f -> f ()
That said, exposing F# function type to C# in any way is a bad pattern and it shouldn't be done. When you have some F# API that is supposed to be used from C#, you should expose functions as delegates, so that C# consumers can use them naturally (without converting Action to F# function explicitly). It is generally easier to write the wrapping on the F# side.
Either:
Add a signature file, with val foo : Action<Action> -> ((unit -> unit) -> unit).
Use a static member of a nominal type, rather than a let-bound value in a module. That is, static member foo (x:Action<Action>) : ((unit -> unit) -> unit) = ...
something like this?
open System
let foo(x : Action<Action>) : (unit -> unit) -> unit = failwith "..."
So I just wanted to ask why this works :
let internal X th =
foo()
th()
bar()
let Start() =
X <| fun () -> ( foo(); bar(); etc... )
And this doesn't work :
let internal XD A =
let X th =
foo()
th()
bar()
(X <| fun () -> A)
let Start() =
XD ( foo(); bar(); etc... )
it's looking like the same for me but first variant works as wrapper and I completely can't understand how second variant works.
I suppose that the confusing thing is that in your second version, the variable A is just a unit. The F# compiler infers this from the fact that you return A from a function that's used as th and the type of th is unit -> unit. This means that foo is called in Start before stepping in XD.
However, it is a bit difficult to tell what results were you expecting. Did you want to pass foo to XD as a function, instead of calling it immediately? If yes, then you'd need:
let internal XD A =
let X th =
foo()
th()
bar()
(X <| fun () -> A()) // Change: Call A with unit argument: 'A ()'
XD foo // Change: Pass a function instead of calling it
The below is the correct code for 2nd version for what you want to achieve (without lambda using lazy values).
let internal XD (A:Lazy<unit>) =
let X th =
foo()
th()
bar()
X <| (fun () -> A.Force())
let Start() =
XD ( lazy(foo(); bar();) )
Given:
C = case A of
undefined ->
"";
Value ->
Value
end
How would I express this as a single line?
Besides the obvious (putting all of that code on one line), you could make a helper function like this:
with_default(undefined, D) -> D;
with_default(X, _) -> X.
with_default(X) -> with_default(X, "").