type Cell = object
x,y:int
let Size = 2345
#...
for i in countup(1,Map.high,2):
for j in countup(1, Map[i].high,2):
var direction = random.sample( [if j+1 > 0 and j+1 < Size: Cell(x:j+1, y:i) else: NaN, if i+1 > 0 and i+1 < Size: Cell(x:j, y:i+1) else: NaN] )
/home/max/project/maze_generator/maze.nim(30, 91) Error: type mismatch: got <float64> but expected 'Cell = object'
why do i get this error? What is wrong? Help me pls
When you use if as an expression like
var res = if cond: x else: y
the x and y have to have the same type. Seems to be obvious in a statically type language, but I think I will add a note in my book.
NaN is floating point. So something = if (condition): foo else: bar can't work if 'foo' is of different type than the type of 'bar'.
You can use if (condition): Cell(x:j+1, y:i) else: Cell(-1, -1) or another "special Cell" to indicate what you wanted to indicate using NaN.
that's, you want to say my code won't work the way i want? If "if" expression can't return "nothing" when the condition is false, then my code won't work correctly, because even it will return, for example, Cell(x:j,y:i), then return.sample can select it and delete current (unwanted) cell.
I just wanted to shorten this code
Directions = newSeq[Cell]()
if i-1 > 0 and i-1 < Size:
Directions.add(Cell(x:j, y:i-1))
if j+1 > 0 and j+1 < Size:
Directions.add(Cell(x:j+1, y:i))
if not (j+1 > 0 and j+1 < Size) and not (i-1 > 0 and i-1 < Size):
Directions.add(Cell(x:j,y:i))
var Direction = random.sample(Directions)
akavel, like this?:
Direction = random.sample( filter( [(if j+1 > 0 and j+1 < Size: some(Cell(x:j+1, y:i)) else: none(Cell)), (if i+1 > 0 and i+1 < Size: some(Cell(x:j, y:i+1)) else: none(Cell))], proc(x:Option[Cell]): bool = x.isSome ) )
Why do you intent to use option[Cell] at all?
I have never used option types myself, but I would assume that there is some overhead involved. Or do you think there is not?
You have the Cell object with x and y fields of type integer. So it should be possible to define a x, y combination that is a invalid state, maybe x, y both with value int.high. Whenever your proc returns that invalid state you can detect it, you can declare your own isNil() or isInvalid() proc for Cell data type and check for invalid state. But well, option types may be fun, I would assume that they work with hidden tuples? I should read more about them.
do you intent to use option[Cell] at all?
I can also use filterIt.
Direction = random.sample( filterIt( [(if j+1 > 0 and j+1 < Size: some(Cell(x:j+1, y:i)) else: none(Cell)), (if i+1 > 0 and i+1 < Size: some(Cell(x:j, y:i+1)) else: none(Cell))], it.isSome) )
and I intent to use it