pichi

pichi

How to define recursive anonymous function in Elixir?

How can I define the recursive anonymous function in Elixir? In Erlang, I can write:

1> F = fun X([]) -> []; X([H|T]) -> [H+1|X(T)] end.
#Fun<erl_eval.20.79398840>
2> F([5,41,13]).
[6,42,14]

I can’t find in documentation a way how to write a similar function in Elixir.

First Post!

LostKobrakai

LostKobrakai

Afaik this is not supported in elixir.

Most Liked

John-Goff

John-Goff

I’m not sure I follow honestly. Could you give a more realistic example of what you’re trying to do if the above was too trivial?

Logan

Logan

f = fn
  ([], _fun) ->
    []
  ([h | t], fun) ->
    [h+1 | fun.(t, fun)]
  end

f.([1, 2, 3], f)
John-Goff

John-Goff

In elixir, unlike in Erlang, you can define modules in the shell. So when you do need to write a recursive function you can do

iex> defmodule Rec do
...>   def recurse([]), do: []
...>   def recurse([h | t]), do: [h + 1 | recurse(t)] 
...> end

Last Post!

dom

dom

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31525 112
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New

We're in Beta

About us Mission Statement