The Inko programming language forum

Info on how to use libraries or modules


#1

I’m looking for info on e.g. how to read a file line-by-line, how to split each line into space-separated words, and how to interpret those strings as floating point numbers.


#2

@jkleiser

At the moment the standard library is rather limited, and there is no online documentation for it yet.

Currently the only mechanisms provided for reading from a file are through the std::io::Read trait, which provides:

  • read_bytes(bytes: ByteArray, size: ?Integer = Nil) !! std::io::Error -> Integer
  • read_string(size: ?Integer = Nil) !! std::io::Error -> String

You would use these along the lines of the following:

import std::fs::file
import std::stdio::stdout
import std::mirror

# This uses the mirror API to obtain the file path of this module. In
# upcoming releases you can use `mirror.reflect_module(ThisModule).path`
# instead.
#
# We're using this because it is the only file that we can guarantee exists,
# making it easier for users to try this example.
let current_file_path = mirror.reflect_block({}).path

let handle = try! file.read_only(current_file_path)
let data = try! handle.read_string

stdout.print(data)

String splitting is not yet supported either, you’d have to implement this manually. This roughly comes down to something like this:

import std::stdio::stdout
import std::byte_array::ByteArray

let space_byte = 32
let input = 'foo bar baz'

let input_bytes = input.to_byte_array
let strings = []
let buffer = ByteArray.new

input_bytes.each do (byte) {
  byte == space_byte
    .if true: {
      strings.push(buffer.to_string)
      buffer.clear
    }, false: {
      buffer.push(byte)
    }
}

# Consume any remaining bytes (after the last space).
strings.push(buffer.to_string)
buffer.clear

stdout.print(strings.inspect)

This is not very efficient, but it’s how you would currently implement this.

Converting a String to a Float isn’t supported either. I think this is fairly easy to support, all we’d need to do is add a VM instruction for this and wrap it. I created the following issue to track this: https://gitlab.com/inko-lang/inko/issues/134.


#3

Thanks, Yorick! I will try this as soon as I find some time. :wink: