V: Function inside a function

Created on 28 Dec 2019  路  8Comments  路  Source: vlang/v

fn double(i int) int{
 fn g(n int) int {
  return n+i
 }
 return g(i)
}
fn main() {
 println(double(1))
}

I want to build success but it showed

unexpected token: `fn`
    1| fn double(i int) int{
Feature Request Won't Fix

Most helpful comment

Might as well be perfect to just have anonymous functions assigned to a variable

All 8 comments

yes, yes, i really wished we could have that!

Might as well be perfect to just have anonymous functions assigned to a variable

agree with @nedpals 鈽濓笍

Take as look at "https://en.wikipedia.org/wiki/Nested_function". It provides for elegant programs and less global variables.

This will work like in Go and like @nedpals suggested: anonymous functions assigned to a variable.

Look, we aren't trying to duplicate what Javascript and other programming languages did with multiple ways of writing a function inside a function and it makes so much sense to this:

fn double(i int) int{
 g := fn (n int) int {
  return n+i
 }
 return g(i)
}
fn main() {
 println(double(1))
}

than the example you have suggested. It's clear and easier to parse both by the user and v compiler.

I agree with @nedpals. This would reduce redundancy and might also be a clear answer to https://github.com/vlang/v/issues/163 . I personally think that having anonymous functions is good enough for both of these things.

As mentioned above, the way to do it in V would to be assigning a lambda to a variable.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

radare picture radare  路  3Comments

radare picture radare  路  3Comments

aurora picture aurora  路  3Comments

vtereshkov picture vtereshkov  路  3Comments

taojy123 picture taojy123  路  3Comments