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

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

We're in Beta

About us Mission Statement