How to require a file

suppose I have a script in one file App.ex

defmodule Foo do
  def sum(a, b) do
    a + b
  end
end

defmodule Bar do
  def cal(a, b, c) do
    Foo.sum(a, b) * c
  end
end

IO.puts Bar.cal 1,2,

now, I want to split it in to 3 single file: Foo.ex, Bar.ex, App.ex
some language just import ‘./path’, but I can’t do it in Elixir, and tried to find the answer in elixir-doc
It seams the only way its to use mix to build a project, it’s a opinionated way for me. So any idea?

Greetings,

First of all you should use code tags to make the code you post readable, I fixed up your post to demonstrate (see the edit log to see how it is done, standard markdown like what is at Github and so forth).

Second, you import by importing the name of the module. The filename does not matter one iota. :slight_smile:

Thus from bar you have Foo.sum, that will still work. When you have compiled (manually if not using mix, that is fine) and loaded the binary modules into the runtime then it will work fine. If you want to import then you could change Bar to this for example:

defmodule Bar do
  import Foo
  def cal(a, b, c) do
    sum(a, b) * c
  end
end

It is all in the Getting-Started section of the manual. :slight_smile:

1 Like

Mix is elixir’s build tool. Can you elaborate on opinions that mix has that you disagree with? About the only actual opinion I know of is that there’s a mix.exs file, and a lib directory.

1 Like

Technically even that is optional, it can be renamed in the mix.exs file. ^.^

1 Like

BIg thanks!

I just notice the compile things. I manually compile the scripts, it works well. And I find that, I can use the command to load multiple files elixir -r foo.ex -r bar.ex app.ex