-1

I'm working on an Io problem that involves the Fibonacci sequence. I'm trying to create a method that tests if a number is a Fibonacci number or not. I can't figure out why my IsAFib method isn't working, does anyone know why and what I can do to fix it? I'm really new to Io, and pretty new to programming too, so if you could be descriptive with your reasons for changing things, I would really appreciate it! I want to know what it needs to be different, not just what it should be written as.

            OperatorTable addOperator("xor", 11)
            true xor := method(bool, if(bool, false, true))
            false xor := method(bool, if(bool, true, false)) 

            doFile("isASquare.io");

Then the isASquare.io file:

            isASquare := method(n,                    
                    for(i, 1, n, 
                        if(i * i == n, return true)
                        if(i * i > n, return false)
                    )
            )

            isAFib := method(n,
                    if(isASquare(2 ** 5 * n) xor isASquare(2 ** n * 5 - 4), return true, return false)
            )
  • Shouldn't it be `return isASquare(2**n * 5 + 4) xor isASquare(2**n * 5 - 4)` according to [Wikipedia](http://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers)? – Bergi Mar 30 '13 at 14:32
  • @Bergi I think I want it to return true or false though, so that I can use it in my next methods. Would xor even work with something like return? – user2220574 Mar 30 '13 at 22:38

1 Answers1

2

So this is a problem that comes up every now and then. The way dynamic operators work is that when the vm loads a source file, before we evaluate any of it, we apply the rules that surround operators. At first run, io only knows about its built in operators. Once this message reordering is done, then we'll start to evaluate the code in the file, i.e., this line first:

OperatorTable addOperator("xor", 11)

By the time this code is run, it's too late for it to have any effect on this file.

The general consensus amongst the community is to put all your operators in a file you load first, and at the end of that file, have it doFile() or similarly have it load your main file which will use them.

It's a bit of a pain in the ass, but in Io there is no traditional compile time.

jer
  • 20,094
  • 5
  • 45
  • 69
  • I've separated it into two files and added doFile() but I keep getting the exception: syntax error near unexpected token `9' whenever I try to run either method with the number 9, etc. – user2220574 Mar 29 '13 at 16:28
  • Ok, using just that code, I can say "works here". My code contains exactly two files, which correspond to your two source examples above. I run: `io -i file1.io` which has the operator table stuff in it, and then run `isAFib(9)` and `isAFib(3)` ... works as I'd expect; and by that I mean, returns true or false, no errors. – jer Mar 31 '13 at 04:01