Skip to content

Instantly share code, notes, and snippets.

@elbow-jason
Created November 5, 2020 20:48
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 elbow-jason/9437018f6b2b0285439f1fce13cd5748 to your computer and use it in GitHub Desktop.
Save elbow-jason/9437018f6b2b0285439f1fce13cd5748 to your computer and use it in GitHub Desktop.
Why are `fox3` and `the2` null?
~/W/z/playground $ zig version
0.6.0+342ba960f
~/W/z/playground $ zig build-exe tfidf.zig
~/W/z/playground $ ./tfidf
word "the" initialized to count 1
after word "the" map count is 1
word "quick" initialized to count 1
after word "quick" map count is 2
word "brown" initialized to count 1
after word "brown" map count is 3
word "fox" initialized to count 1
after word "fox" map count is 4
word "fox" initialized to count 1
after word "fox" map count is 5
word "fox" initialized to count 1
after word "fox" map count is 6
word "jumped" initialized to count 1
after word "jumped" map count is 7
word "over" initialized to count 1
after word "over" map count is 8
word "the" initialized to count 1
after word "the" map count is 9
word "lazy" initialized to count 1
after word "lazy" map count is 10
word "dog" initialized to count 1
after word "dog" map count is 11
fox3 count is null
the2 coutn is null
const std = @import("std");
const Allocator = std.mem.Allocator;
const mem = std.mem;
const Map = std.AutoHashMap([]const u8, usize);
pub fn main() !void {
const allocator = std.heap.page_allocator;
var map = Map.init(allocator);
defer map.deinit();
const phrase = "the quick brown fox fox fox jumped over the lazy dog";
var it1 = mem.split(phrase, " ");
while (it1.next()) |word| {
var result = try map.getOrPut(word);
if (result.found_existing) {
result.entry.value += 1;
std.debug.print("word {s} found with count {d}\n", .{word, result.entry.value});
result.entry.value += 1;
std.debug.print("word {s} set to count {d}\n", .{word, result.entry.value});
} else {
result.entry.value = 1;
std.debug.print("word \"{s}\" initialized to count {d}\n", .{word, result.entry.value});
}
std.debug.print("after word \"{s}\" map count is {d}\n\n", .{word, map.count()});
}
const fox3 = map.get("fox");
const the2 = map.get("the");
std.debug.print("fox3 count is {d}\n", .{fox3});
std.debug.print("the2 coutn is {d}\n", .{the2});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment