return result
proc pluser(x:int, y:int):int = x + y
var zs = zipwith(pluser,[1,2,3],[1,2,3]))
This code produces "Error: invalid type: 'openarray[int]'"
Also, the reason I wrote the silly "pluser" procedure is because I get another error when I try to pass the + operator directly. Shouldn't I be able to do this?
var zs = zipwith(+,[1,2,3],[1,2,3]))
Thanks.
proc zipwith[T1,T2,T3](f: proc(a:T1,b:T2):T3, xs:openarray[T1],
ys:openarray[T2]): seq[T1] =
newSeq(result, xs.len)
for i in low(xs)..high(xs):
result[i] = f(xs[i],ys[i])
proc pluser(x:int, y:int):int = x + y
var zs = zipwith(pluser,[1,2,3],[1,2,3])
Thanks for the clarification. I guess the size of the array must be able to be determined at compile time, or we must use a sequence.
Exactly. A sequence is an array on the heap.
When you use templates, you can also use +.
template zipwith[T1,T2](f: untyped; xs:openarray[T1], ys:openarray[T2]): untyped =
let N = min(xs.len, ys.len)
var res = newSeq[type(f(xs[0],ys[0]))](N)
for i, value in res.mpairs:
value = f(xs[i], ys[i])
res
var zs = zipwith(`+`,[1,2,3],[1,2,3])
echo zs