V version: V 0.1.28 e666209
OS: MacOS
What did you do?
I want to compose 2 functions, as follows:
fn sqr(n int) int {
return n*n
}
fn double(n int) int {
return n+n
}
fn compose(f1, f2 fn(int) int) fn(int) int {
return fn(n int) int {
return f1(f2(n))
}
}
fn main() {
f := compose(sqr, double)
println(f(5))
}
What did you expect to see?
In golang, It is work and output 100.
What did you see instead?
But in vlang, It compiled failed and report:
==================
^
/private/var/folders/3l/6gbl43kj0jj6gyngz2hbg7c00000gn/T/v/high_order_fn.tmp.c:1202:13: error: implicit declaration of function 'f2' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
return f1(f2(n));
^
/private/var/folders/3l/6gbl43kj0jj6gyngz2hbg7c00000gn/T/v/high_order_fn.tmp.c:4635:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
/private/var/folders/3l/6gbl43kj0jj6gyngz2hbg7c00000gn/T/v/high_order_fn.tmp.c:4736:27: warning: incompatible pointer types passing 'array_fixed_byteptr_100' (aka 'byteptr [100]') to parameter of type 'void **' [-Wincompatible-pointer-types]
int nr_ptrs = backtrace(buffer, 100);
^~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/execinfo.h:35:21: note: passing argument to parameter here
int backtrace(void**,int) __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
...
==================
(Use `v -cg` to print the entire error message)
builder error:
==================
C error. This should never happen.
@alai04 Closures aren't implemented yet so the scope is limited inside the anonymous function for now.
Got it
We will open this issue for now for tracking.
I use closures often, so lack of it prevents me from start using the language.
I use closures often, so lack of it prevents me from start using the language.
@thearchitect
You can make you own closures until they're implemented:
struct Context {
mut:
v int
}
inc := fn(mut ctx Context) {
ctx.v++
}
mut c := Context{}
inc(mut c)
println(c.v)
I use closures often, so lack of it prevents me from start using the language.
@thearchitect
You can make you own closures until they're implemented:
struct Context { mut: v int } inc := fn(mut ctx Context) { ctx.v++ } mut c := Context{} inc(mut c) println(c.v)
Thank you for you reply, Larpon!
Closures is a good tool to make code more understandable and readable. The pattern you offered works, but it makes opposite effect. So the language need closures.
Most helpful comment
Thank you for you reply, Larpon!
Closures is a good tool to make code more understandable and readable. The pattern you offered works, but it makes opposite effect. So the language need closures.