Haskell GHCI compiler: Parse error in repl when defining and declaring a simple function

StackOverflow https://stackoverflow.com/questions/21943406

  •  14-10-2022
  •  | 
  •  

Вопрос

I'm going through the "Learn You A Haskell" book.

I'm trying to define this simple function but the compiler is spitting it out. It's probably something very basic and simple but I'm a complete Haskell newbie:

GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> doubleMe x = x + x

<interactive>:2:12: parse error on input `='

Prelude>

Это было полезно?

Решение

If you read the book carefully, it says (emphasis mine):

Open up your favorite text editor and punch in this function that takes a number and multiplies it by two.

    doubleMe x = x + x  

Which is fine for ghc, because it can understand that it's a function declaration (and the book didn't tell you to try it in ghci. In fact, shortly after it explains how let can be used "to define a name right in GHCI. Doing let a = 1 inside GHCI is the equivalent of writing a = 1 in a script and then loading it."). To make ghci understand that you are defining a function you need to use let:

Prelude> let doubleMe x = x + x
Prelude> doubleMe 10
20

Другие советы

In GHCi, you bind new identifiers using the let keyword.

> let doubleMe x = x + x
> doubleMe 3
> 6
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top