fibonacci
Some checks failed
Build / build (push) Failing after 2m11s
Test / build (push) Failing after 2m10s

This commit is contained in:
Chuck Smith
2024-03-14 20:11:29 -04:00
parent cc78fee3c8
commit 36f04713bd
2 changed files with 90 additions and 10 deletions

76
main.go
View File

@@ -1,19 +1,75 @@
package main package main
import ( import (
"flag"
"fmt" "fmt"
"monkey/repl" "time"
"os"
user2 "os/user" "monkey/compiler"
"monkey/evaluator"
"monkey/lexer"
"monkey/object"
"monkey/parser"
"monkey/vm"
) )
func main() { var engine = flag.String("engine", "vm", "use 'vm' or 'eval'")
user, err := user2.Current()
if err != nil { var input = `
panic(err) let fibonacci = fn(x) {
if (x == 0) {
0
} else {
if (x == 1) {
return 1;
} else {
fibonacci(x - 1) + fibonacci(x - 2);
} }
fmt.Printf("Hello %s! This is the Monkey programmig language!\n", user.Username) }
fmt.Printf("Feel free to type in commands\n") };
repl.Start(os.Stdin, os.Stdout) fibonacci(35);
`
func main() {
flag.Parse()
var duration time.Duration
var result object.Object
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
if *engine == "vm" {
comp := compiler.New()
err := comp.Compile(program)
if err != nil {
fmt.Printf("compiler error: %s", err)
return
}
machine := vm.New(comp.Bytecode())
start := time.Now()
err = machine.Run()
if err != nil {
fmt.Printf("vm error: %s", err)
return
}
duration = time.Since(start)
result = machine.LastPoppedStackElem()
} else {
env := object.NewEnvironment()
start := time.Now()
result = evaluator.Eval(program, env)
duration = time.Since(start)
}
fmt.Printf(
"engine=%s, result=%s, duration=%s\n",
*engine,
result.Inspect(),
duration)
} }

View File

@@ -755,3 +755,27 @@ func TestRecursiveFunctions(t *testing.T) {
runVmTests(t, tests) runVmTests(t, tests)
} }
func TestRecursiveFibonacci(t *testing.T) {
tests := []vmTestCase{
{
input: `
let fibonacci = fn(x) {
if (x == 0) {
return 0;
} else {
if (x == 1) {
return 1;
} else {
fibonacci(x - 1) + fibonacci(x - 2);
}
}
};
fibonacci(15);
`,
expected: 610,
},
}
runVmTests(t, tests)
}