0

I've got a text file with the following code:

fib 0 = 1

fib 1 = 1 

fib n = fib (n-1) + fib (n-2)

evenOdd n = if (mod n 2) == 0 then 1 else 0

sumFib 0 = 0

sumFib 1 = 0

sumFib n = (evenOdd (fib n))*(fib n) + sumFib (n-1)

Basically, I'm trying to define three functions, where the third relies on the first two. However, when I load this in GHCi, while fib works fine, evenOdd gives me the following error:

interactive>:1:1:1 error: Variable not in scope: evenOdd :: Integer -> t

This confuses me, because if I type that exact line of code into *Main>, evenOdd works fine. How can I get this to work?

5
  • 1
    Are you sure you are importing correctly / have saved your file before importing? Both functions work fine here. *Main> evenOdd 202 gives 1 and *Main> fib 21 gives 17711 Commented Jan 3, 2018 at 7:21
  • 1
    Not reproducible, voting to close. Commented Jan 3, 2018 at 7:34
  • Unfortunately, I'm still getting the error, when I use :l and the filename (and GHCi says that the file loaded correctly). Commented Jan 3, 2018 at 7:35
  • You could try and :edit filename.hs to check if you are actually loading the right file. Maybe you are in the wrong directory / loading up an old version / didn't save properly. Commented Jan 3, 2018 at 7:39
  • Unrelated, but: evenOdd n = mod n 2, or evenOdd = (`mod` 2) if you're zealous about point-free. The if/then/else is unneeded extra work. Of course, the wasted/duplicated work in fib and sumFib is going to dwarf that... Commented Jan 3, 2018 at 9:15

1 Answer 1

2

On my ghci everything seems to work fine. As you can use fib I'm sure you loaded the file correctly but it seems like you didn't save after adding evenOdd to the file before actually loading.

Try:

  • Save file first
  • :l filename.hs
  • evenOdd 10

This worked on my device. If for some reason this is still not working, you could try and run a :edit filename.hs to see what file you are actually loading in. Maybe this file is a different one / different version than you expected it to be.

My terminal output:

➜  Desktop ls
PO.pptx     untitled.hs
➜  Desktop ghci
GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> :l untitled.hs
[1 of 1] Compiling Main             ( untitled.hs, interpreted )
Ok, 1 module loaded.
*Main> fib 20
10946
*Main> evenOdd 2023
0
*Main> evenOdd 2
1
*Main> 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It ended up being a saving problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.