Guest User

Untitled

a guest
Apr 16th, 2018
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. const std = @import("std");
  2. const warn = std.debug.warn;
  3.  
  4. fn Iterator(comptime T: type) type {
  5. return struct {
  6. const Self = this;
  7.  
  8. next_fn: fn(self: &Self) ?T,
  9.  
  10. fn next(self: &Self) ?T {
  11. return self.next_fn(self);
  12. }
  13. };
  14. }
  15.  
  16. fn filter(comptime predicate: var) {
  17. const FnType = @typeOf(predicate);
  18.  
  19. if (@typeId(FnType) != TypeId.Fn) {
  20. @compileError("Filter expect a function paramater");
  21. }
  22.  
  23. if (FnType.arg_count != 1) {
  24. @compileError("Filter expects a function with one argument.");
  25. }
  26.  
  27. if (FnType.ReturnType != bool) {
  28. @compileError("Filter expect a function that returns a bool");
  29. }
  30.  
  31. const T = @ArgType(FnType, 0);
  32.  
  33. //both Iterators have the same `items`, whatever you wanna call it.
  34. const InputIt = Iterator(T);
  35. const OutputIt = Iterator(T);
  36.  
  37. return struct {
  38. const Self = this;
  39. it: OutputIt,
  40. input_it: &InPutIt,
  41.  
  42. fn init(input_it: &InputIt) Self {
  43. return Self {
  44. .it = OutPutIt {
  45. .next_fn = next,
  46. },
  47. .input_it = InputIt,
  48. };
  49. }
  50.  
  51. fn next(it: &OutPutIt) ?T {
  52. const self = @fieldParentPtr(Self, "it", it);
  53. const val = self.input_it.next() ?? return null;
  54.  
  55. if (predicate(val)) {
  56. return val;
  57. }
  58. return null;
  59. }
  60. };
  61. }
Advertisement
Add Comment
Please, Sign In to add comment