Pular para o conteúdo

Arrays em Wasm

Nesta página

O backend AOT suporta arrays dentro de funções: literais, indexação (base 0), len(), for-in e push. Há uma limitação atual: um let no nível superior ainda não é suportado (seria rebaixado para uma global); mantenha o código com arrays dentro de funções — locais funcionam normalmente.

Funções @export podem receber e retornar arrays escalares de um nível: [int], [bool] e [str]. Os tipos espelhados no JS são number[], boolean[] e string[], respectivamente. Do lado do consumidor:

import init, { total, evens, shout } from "./04-arrays.js"
await init()
total([1, 2, 3, 4])         // 10
evens([1, 2, 3, 4, 5, 6])  // [2, 4, 6]
shout(["a", "b"])           // ["a!", "b!"]

O exemplo abaixo mostra as três funções exportadas e um bloco de demonstração em linguagem pura — chamando total a partir de fn demo() para verificar o comportamento dentro do Zolo antes de cruzar a fronteira wasm:

Arrays em @export: [int]→int, [int]→[int] e [str]→[str].

04-arrays.zolo
Playground
// Feature: arrays in AOT wasm + `@export` of array types

// Build (AOT, browser):

//   zolo build 32-webassembly/04-arrays.zolo --emit wasm --host browser --aot \

//     -o 32-webassembly/target/04-arrays.wasm

//

// In-language arrays work under --aot: literals, indexing (0-based), len(),

// for-in, and push. NOTE: a `let` at the top level isn't supported yet (it

// lowers to a global); keep array code inside a function (locals work).

//

// `@export fn`s can take/return one-level scalar arrays — [int], [bool], [str]:

//   import init, { total, evens, shout } from "./04-arrays.js"

//   await init()

//   total([1, 2, 3, 4])      // 10

//   evens([1, 2, 3, 4, 5, 6])// [2, 4, 6]

//   shout(["a", "b"])        // ["a!", "b!"]

// (number[] <-> [int], boolean[] <-> [bool], string[] <-> [str].)


@export fn total(xs: [int]) -> int {
  let mut s = 0
  for x in xs { s = s + x }
  return s
}

@export fn evens(xs: [int]) -> [int] {
  let mut o = []
  for x in xs {
    if x % 2 == 0 { o.push(x) }
  }
  return o
}

@export fn shout(xs: [str]) -> [str] {
  let mut o = []
  for s in xs { o.push("{s}!") }
  return o
}

// In-language demo (arrays used entirely inside a function):

fn demo() {
  let xs = [1, 2, 3, 4]
  print("sum = {total(xs)}")
}
demo()

// expected (run natively): sum = 10

Requer a CLI/host do Zolo — abra no playground ou rode localmente.

Desafio

Adicione uma função @export fn sum_of_evens(xs: [int]) -> int que filtra os pares e soma o resultado. Teste-a a partir do JS com [1, 2, 3, 4, 5, 6] e confirme que o retorno é 12.

Buscar no Zolo

9 resultados

enespt-br