Arrays en Wasm
En esta página
El backend AOT soporta arrays dentro de funciones: literales, indexación
(base 0), len(), for-in y push. Hay una limitación actual: un let en
el nivel superior aún no está soportado (sería reducido a una global); mantén
el código con arrays dentro de funciones — las locales funcionan normalmente.
Las funciones @export pueden recibir y retornar arrays escalares de un nivel:
[int], [bool] y [str]. Los tipos espejados en JS son number[],
boolean[] y string[], respectivamente. Desde el lado del 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!"]
El ejemplo a continuación muestra las tres funciones exportadas y un bloque de
demostración en lenguaje puro — llamando a total desde fn demo() para
verificar el comportamiento dentro de Zolo antes de cruzar la frontera wasm:
Arrays en @export: [int]→int, [int]→[int] y [str]→[str].
// 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
Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.
Desafío
Añade una función @export fn sum_of_evens(xs: [int]) -> int que filtre los
números pares y sume el resultado. Pruébala desde JS con [1, 2, 3, 4, 5, 6]
y confirma que el valor de retorno es 12.
Consulta también