#How to write an ArrayList.contains function

1 messages · Page 1 of 1 (latest)

glacial eagle
#

Since ArrayList and their managed friends are getting deprecated at some point,
I'm writing my own implementation of ArrayList, but with some other features I'm used to from other langs

One of them is being able to check if a list contains an item
Using std.mem.indexOfScalar(T, S.buffer.items, item) != null; works fine for scalars,
but I don't know how to deal with other cases, such as the arraylist holding []T instead of just T

Is there any feature in the stdlib that I could use to implement this string_list.contains("example"); functionality, in a way that also works for other generic []T?

cerulean fossil
#

std.mem.indexOf?

#

That takes a needle slice and haystack slice

full token
#

iiuc they need something that searches a [][]T, not []T for a subslice

#

i dont think theres much of anything for this, you could do something where .contains takes a T just assuming its comparable than have a second one that accepts a function that does the comparison so users can decide how it searches

#

though at that point its not much different from them just using their function

glacial eagle
#

could be useful if they provide the function once on type generation, I guess

fluid vine
glacial eagle
fluid vine
#

okay I guess, I just don't really get how it's related to the deprecation 🤷‍♀️

glacial eagle
#

deprecation just pushed me to finally make my own api

thorny salmon
#

for string_list.contains("example"); you can look at how hashmap work. Basically you need to provide a function to compare the two strings. Either in the type signature or through a function pointer

signal kindle
#

but no the std lib doesnt have any function like deepEql

stone aurora
#

Are you looking for something like this?

const std = @import("std");

pub fn MyArrayList(comptime T: type) type {
    return struct {
        items: []T,
        allocator: std.mem.Allocator,
        // ... other fields, append, indexOf, etc. 

        /// contains example. 
        pub fn contains(self: @This(), item: T) bool {
            for (self.items) |elem| {
                if (std.meta.eql(elem, item)) return true;
            }
            return false;
        }
    };
}
/ ...

var list = MyArrayList(i32).init(std.testing.allocator);
defer list.deinit();

try list.append(10);
if (list.contains(10) {
  // ...
}
glacial eagle
#

I only knew std.mem.eql, and didn't know about std.meta.eql. tysm 👌

full token
#

dont think its very useful for you considering the last sentence in the docs

glacial eagle
#

why so?