Created
January 19, 2018 20:06
-
-
Save andrewrk/ed2fe32c7142611f5a68afdba1dcb35d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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