by jeremyjh · 5y ago · 0 comments
Not really. Named functions live in modules because that is how it is done in Erlang; Elixir is compiled to Erlang's abstract syntax. In practice does anyone define Clojure functions outside of a namespace? Haskell functions are always defined in modules too, do you think they got that from class based languages?
Clojure REPLS allow switching the namespace, and anything you define goes intoo the current namespace. So it is more ergonomic.
iex(1)> defmodule Foo, do: def bar(x), do: x + 1
{:module, Foo,
<<70, 79, 82, 49, 0, 0, 4, 192, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 135,
0, 0, 0, 15, 10, 69, 108, 105, 120, 105, 114, 46, 70, 111, 111, 8, 95, 95,
105, 110, 102, 111, 95, 95, 10, 97, 116, ...>>, {:bar, 1}}
iex(2)> Foo.bar(1)
2
iex(3)> import Foo
Foo
iex(4)> bar(1)
2In clojure, it is:
user> (defn bar [x] (+ x 1))
If you want it inside a namespace named foo, then it is: user> (in-ns 'foo)
foo> (defn bar [x] (+ x 1)) >bar = fn x -> x + 1 end
The most unfortunate thing though is then you have to have a different calling convention. Its the greatest flaw in Elixir by far but they didn't have a reasonable alternative given the constraints of Erlang.Still for defining a named function in the REPL its the same in Haskell and most other languages I believe that you can't define a new named function or add a function to a module in the REPL, though at least in Haskell the calling convention for a variable bound to a lambda is the same as for a named top-level function. LISPs have always had a different notion of how the REPL integrates into the development experience of a running program, and I don't think its really been replicated elsewhere.
In Clojure too, the fns, records everything live inside a namespace but that is a modularity mechanism for code organisation.