Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created January 19, 2018 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrk/ed2fe32c7142611f5a68afdba1dcb35d to your computer and use it in GitHub Desktop.
Save andrewrk/ed2fe32c7142611f5a68afdba1dcb35d to your computer and use it in GitHub Desktop.
const std = @import("std");
/// Can return error.OutOfMemory
/// Caller owns the returned memory
fn map(allocator: &std.mem.Allocator, comptime T: type, items: []const T, func: fn(T)->T) -> %[]T {
const new_items = try allocator.alloc(T, items.len);
%defer allocator.free(new_items);
for (items) |item, i| {
new_items[i] = func(item);
}
return new_items;
}
fn addOne(x: i32) -> i32 { return x + 1; }
test "basic usage of map" {
var data = []i32{1, 2, 3};
const new_data = try map(std.debug.global_allocator, i32, data[0..], addOne);
std.debug.assert(new_data[0] == 2);
std.debug.assert(new_data[1] == 3);
std.debug.assert(new_data[2] == 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment