PragTob

PragTob

User defined function, recursion and passing self along

Hey everyone!

This is a multi-layered question and I’ll try my best to try and phrase it cleanly.

As an abstract use case I want to have a function that is adjustable in its behaviour by a caller by passing in an optional function (think Map.merge/3). This function is used to determine what my function does - but it’s not all, it is wrapped and calls a Protocol function on a specific return value. This protocol function might want to call the previous method, hence it requires me to pass along the initially user supplied function… I’d much prefer to be able to create an anonymous function that already is the “wrapped” version of the user supplied function but can’t seem to do it because of recursion…

in code:

  # in the module MyModule
  def original_method(argument, user_function) do
    val = user_function.(argument)
    case val do
       @continue_symbol ->
        MyProtocol.continue(argument, user_function)
      _anything ->
        val
    end
  end

  # MyProtocol
  def continue(argument, fun) do
    resolver = fn(argument) -> original_method(argument, fun) end
    Stdlib.function(argument, resolver)
  end

I’d love the whole of original_method to be an anonymous function by itself (built from my code + the user supplied function), but it seems impossible as it would have to pass itself along to the function it calls on the protocol.

It just feels strange overall. I can’t have it as a nice already wrapped anonymous function and even in the protocol I seem to always have to build my own resolver function calling back to original_method.

Does anyone know of a better way to do this? The concrete code can be found here and the two methods are basically DeepMerge.Integration.do_deep_merge (still working on naming…) and the implementations for DeepMerge.Resolver.resolve. The use case is basically that normally the protocols for each data type know how to resolve the deep_merge, but the user has a shot at changing that behaviour should she choose to (e.g. don’t merge lists).

Thanks a lot for reading this far and helping out, any feedback appreciated :slight_smile: !
Tobi

Marked As Solved

tomekowal

tomekowal

This is a known problem in functional languages. How to make a recursive anonymous function?
Even something as simple as factorial is hard to write:

fac = fn(0) -> 1
            (n) -> fac.(n-1) * n end
** (CompileError) iex:2: undefined function fac/1

There are topics abou it on Erlang mailing list and there is this in particular:
http://erlang.org/pipermail/erlang-questions/2003-January/006639.html
and it shows a trick to get around that limitation:

fac = fn(0, _f) -> 1
            (n, f) -> f.(n-1) * n end
factorial = fn(n) -> fac.(n, fac) end
factorial.(5)

The good news is this workaround is easy. The bad news is that you would have to teach it to every single user of your library (or just use named functions).

Also Liked

OvermindDL1

OvermindDL1

That style is called the Y-Combinator. There are many kinds of combinators, should look them up. :slight_smile:

gregvaughn

gregvaughn

Here’s a great resource to learn about combinators in general, if Ruby as a sample language works for you: Kestrels, Quirky Birds, and Hopeless Egocentricity

JEG2

JEG2

Author of Designing Elixir Systems with OTP

Yeah, I’m totally explaining and not defending this design choice. :smile:

OvermindDL1

OvermindDL1

No need for lisp, just normal functional stuff. :slight_smile:

I usually just point people to the wikipedia article, short, to the point for each combinator: Fixed-point combinator - Wikipedia

For Elixir there are libraries that simplify the combinators as well, such as quark, where the Y-Combinator is named fix for being a fixed-point combinator, but it shows a lot of other non-fixed point combinators as well (that same author makes a lot of awesome libraries like that, especially for functional design, click their name on the lower-right of that page too, especially as a lot of their libs are designed to be used together). :slight_smile:

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

We're in Beta

About us Mission Statement