Morgen Yang
Morgen Yang

Reputation: 333

Why is "Variable not in scope"

What's the problem with code.

My Haskell platform is new . And I have tried to adjust the formats for many times. But it didn't work all the time.

import Data.Char
import Data.List

encode :: Int -> String -> String
encode shift msg =
    let ords = map ord msg
    shifted = map (+ shift) ords
    in map chr shifted

The result is always like this

Prelude> :r
Ok, no modules loaded.
Prelude> :type encode

<interactive>:1:1: error: Variable not in scope: encode

When I load my files, it shows

Prelude> :l H2-2.hs
[1 of 1] Compiling Main             ( H2-2.hs, interpreted )

H2-2.hs:56:3: error: parse error on input ‘shifted’
   |
56 |   shifted = map (+ shift) ords
   |   ^^^^^^^
Failed, no modules loaded.

Upvotes: 2

Views: 4523

Answers (1)

AJF
AJF

Reputation: 11913

There's an indentation error in your code. Here it is corrected:

encode :: Int -> String -> String
encode shift msg =
    let ords = map ord msg
        shifted = map (+ shift) ords
    in map chr shifted

In blocks like let ... in ... or where ..., do ... etc, it's important to not allow the indentation of subsequent lines to fall behind the indentation of the first – this is called the ‘offside rule,’ and it's how Haskell determines what belongs in what block.

Start up GHCi with ghci H2-2.hs or write :l H2-2.hs to load the file. Once it's loaded, if you want to load some additional changes, only then should you use :r.

Upvotes: 5

Related Questions