Skip to content

Instantly share code, notes, and snippets.

@nima
Last active December 27, 2016 00:19
Show Gist options
  • Save nima/a7fa0152f35341bfeb0b1e9abfc11784 to your computer and use it in GitHub Desktop.
Save nima/a7fa0152f35341bfeb0b1e9abfc11784 to your computer and use it in GitHub Desktop.
C, Go, and Pointers
int fn_b(int a, int b) { return a % b; }
int fn_c1(int a, int b, int c) { return a + b + c; }
int fn_c2(int a, int b, int c) { return a * b * c; }
int (*fn_d(int (*x)(int, int), int y))(int, int, int) {
return x(y, 2) ? fn_c1 : fn_c2;
}
int main(int argc, char **argv, char** envp) {
int (*(*f)(int (*)(int, int), int))(int, int, int) = fn_d;
int (*g)(int, int, int) = f(fn_b, argc);
return g(2, 3, 4);
}
package main
import ( "fmt" "os" )
func fn_b(a int, b int) int { return a % b; }
func fn_c1(a int, b int, c int) int { return a + b + c; }
func fn_c2(a int, b int, c int) int { return a * b * c; }
func fn_d(x func(int, int) int, y int) func(int, int, int) int {
if x(y, 2) > 0 { return fn_c1 } else { return fn_c2 }
}
func main() {
var argc int = len(os.Args)
var f func(func(int, int) int, int) func(int, int, int) int = fn_d
var g func(int, int, int) int = f(fn_b, argc)
fmt.Println(g(2, 3, 4)) #. TODO:
}

Background

I came up with this ridiculous problem statement while reading the following blog post:

https://blog.golang.org/gos-declaration-syntax

The function pointer used there to exemplify "difficulties that C's declaration syntax can introduce" is what I've used here as the starting point.

there is the starting point

Problem (Almost-)Definition

  1. Construct some C code that makes use of the following C declaration in some semi-meaningful way:
    int (*(*f)(int (*)(int, int), int))(int, int, int);
  1. Next, translate this into Go, Python, Ruby, Perl, etc.
import sys
def fn_b(a, b): return a % b
def fn_c1(a, b, c): return a + b + c
def fn_c2(a, b, c): return a * b * c
def fn_d(x, y):
return fn_c1 if x(y, 2) else fn_c2
def main():
argc = len(sys.argv)
f = fn_d
g = f(fn_b, argc)
return g(2, 3, 4)
if __name__ == '__main__': sys.exit(main())
def fn_b(a, b) return a % b end
def fn_c1(a, b, c) return a + b + c end
def fn_c2(a, b, c) return a * b * c end
def fn_d(x, y)
return proc {|a, b, c| (x.call(y, 2) > 0 ? fn_c1(a, b, c) : fn_c2(a, b, c))}
end
def main()
argc = ARGV.length
f = proc {|x, y| fn_d(x, y) }
g = f.call(proc {|a, b| fn_b(a, b)}, argc)
exit(g.call(2, 3, 4))
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment