-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathackermann.go
49 lines (42 loc) · 1.07 KB
/
ackermann.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Example library to provide a go implementation of the recursive ackermann function.
* This library can be loaded in PHP using PHP-FFI (https://www.php.net/manual/en/book.ffi.php).
*
* 2 variants of the function are provided:
*
* ackermann(n, m) using integers as input and output
* ackermann_json using json strings as input and output
*
* examples:
* println(ackermann(3, 11));
* println(C.GoString(ackermann_json(C.CString("[3, 11]"))));
*
* compiling: go build -o ackermann.so -buildmode=c-shared ackermann.go
*/
package main
import "C"
import "encoding/json"
func main() {
}
//export ackermann
func ackermann(n int, m int) int {
if n == 0 {
return m + 1
} else if m == 0 {
return ackermann(n-1, 1)
}
return ackermann(n-1, ackermann(n, m-1))
}
//export ackermann_json
func ackermann_json(input *C.char) *C.char {
var params [2]int
err := json.Unmarshal([]byte(C.GoString(input)), ¶ms)
if err != nil {
return nil
}
data, err := json.Marshal(ackermann(params[0], params[1]))
if err != nil {
return nil
}
return C.CString(string(data))
}