In the code below, I get a compile error:
import std/math
type
Allergen* = enum
Eggs, Peanuts, Shellfish, Strawberries, Tomatoes, Chocolate, Pollen, Cats
# 1 , 2, 4, 8, 16, 32, 64, 128
proc allergies*(score: int): set[Allergen] =
var remainder :int = score
var value: int
for allergen in Allergen.high..Allergen.low:
value = 2^int(allergen)
if value <= remainder:
remainder -= value
result.add(allergen) # <--- error here.
return result
proc isAllergicTo*(score: int, allergen: Allergen): bool =
return allergies(score).contains(allergen)
output:
D:\nim\exercism\nim>nim c -r "d:\nim\exercism\nim\allergies\allergies.nim"
Hint: used config file 'C:\Users\madsenbj\.choosenim\toolchains\nim-2.0.0\config\nim.cfg' [Conf]
Hint: used config file 'C:\Users\madsenbj\.choosenim\toolchains\nim-2.0.0\config\config.nims' [Conf]
.............................................................................
d:\nim\exercism\nim\allergies\allergies.nim(16, 13) Error: type mismatch
Expression: add(result, allergen)
[1] result: set[Allergen]
[2] allergen: Allergen
Expected one of (first mismatch at [position]):
[1] proc add(x: var string; y: char)
[1] proc add(x: var string; y: cstring)
[1] proc add(x: var string; y: string)
[1] proc add[T](x: var seq[T]; y: openArray[T])
[1] proc add[T](x: var seq[T]; y: sink T)
What have I missed that makes result.add(allergen) be accepted in add(result, allergen)? I don't understand the traceback.
nim 2.0.0 coming from python.
found another bug in your code:
for allergen in Allergen.high..Allergen.low:
Use countDown() for descending for loops. Slices ".." doesn't work with starting values higher then end.Two more tiny things, for enums you don't need to specify high and low explicitly. Simply doing for allergen in Allergen: works fine.
Secondly the implicit result variable is automatically returned at the end of your proc, so the return result is superfluous. In general you would only use return in Nim for control flow reasons.