2

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.
3
  • 3
    It seems like you never loaded your program, since it says "no modules loaded". Did you run ghci with ghci myfile.hs? Commented May 12, 2019 at 12:53
  • 2
    Prelude> :r Ok, no modules loaded - that makes it looks like you haven't actually loaded your module. You need to do :l <module_name> first (then you don't need :r until you've made modifications and want to reload it). Commented May 12, 2019 at 12:53
  • You can simplify this to encode shift msg = map (chr. (+ shift) . ord) msg; in general, map f (map g xs) == map (f . g) xs. Commented May 12, 2019 at 20:31

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.