I've looked through the docs but haven't found the answer to this.
I have an array of integers (prime numbers) and I want to: 1) determine if some number is included in the array and 2) return the index value of the number in the array.
In Ruby/Crystal I can do the following. What are the equivalent method(s) in Nim?
Ruby
1) primes = [7, 11, 13, 17, 19, 23, 29, 31]
if primes.include? num; do_something_here end
2) index = primes.index num
I tried to do the following in Nim to give me the equivalent result for 1) in Nim, but the compiler squawks.
Nim
1) if count(primes, num) == 1: do_something_here
I expected that count(primes, num) would return 0 if num isn't in primes but the compiler gives type mismatch error.
let primes = [7, 11, 13, 17, 19, 23, 29, 31]
#1
if 7 in primes: echo("Found it!")
#2
echo primes.find(13)
I don't think count does what you think it does. According to the docs it "Returns the number of occurrences of the item x in the container s."
Hope that helps! :D
in is operator in Nim which uses proc contains
If you want to use the in operator, you should provide binary proc contains .
Since contains is widely implemented in various stdlib (it's needed to if we want to use in ), you can check from theindex which one you need.
I suggest you check the contains proc from system module.