toit

Including modules using operator import


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.

  1. I've two files, bs_func.toit, which contains the binary_search function, and bs_test.toit, which uses this function:

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"
  1. I just need to include binary_search in bs_test.toit by means an import statement.
  2. Experiments with the package.lock file ended in failure, so I would just like to get instructions on how to do this in my case.
  3. I am using VCS.

Thanks in advance, MK


Solution

  • Since you refer to package tutorial I'm assuming that you have the following layout:

    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 imports 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
      ...