I've read the "Package tutorial" section and, to be honest and frank, I didn't understand much. But I know exactly what I want to get.
bs_func.toit
binary_search list needle:
from := 0
to := list.size - 1
while from <= to :
mid := (to + from) / 2
if list[mid] == needle :
return mid
else if list[mid] < needle :
from = mid + 1
else if list[mid] > needle :
to = mid - 1
return -1
bs_test.toit
import ???
main:
list := List 16: it * 2
print "Binary Search"
print "List: $list"
number := 8
index := binary_search list number
print "index of $number is $index"
Thanks in advance, MK
Since you refer to package tutorial I'm assuming that you have the following layout:
bs
, but the name isn't relevant,bs_func.toit
inside the src
folder of bs
. So bs/src/bs_func.toit
, andbs_test.toit
inside the test
folder of bs
. So bs/tests/bs_test.toit
.The easiest way to import bs_func.toit
from bs_test.toit
is to dot out, and then go into the src
folder:
import ..src.bs_func // double dot goes from bs/src to bs/, and .src goes into bs/src.
To guarantee that only `binary_search is visible, then one can restrict the import as follows:
import ..src.bs_func show binary_search
A different (and probably preferred) way is to import the bs_func.toit
as if it was part of a package (which it should become anyway). (Note: I will change the tutorial to follow that approach).
You want to start by giving the tests directory a package.lock
file, indicating that import
s should use it to find their targets.
# Inside the bs/tests folder:
toit pkg init --app
This should create a package.lock
file.
We can now import the package with the --local
flag:
# Again in the tests folder
toit pkg install --local --prefix=bs ..
This says: Install the local (--local
) folder ".." (..
) as package with the prefix "bs" (--prefix=bs
).
Now we can use this prefix to import the package (and thus the bs_func.toit
):
import bs.bs_func
main:
...
index := bs.binary_search list number
...
As you can see: just importing the file with bs.bs_func
gives it the prefix bs
. You can avoid the prefix by using show
:
import bs.bs_func show binary_search
main:
...
index := binary_search list number
...