Why can't I define a new type in ghci?

前端 未结 4 1152
花落未央
花落未央 2020-12-30 19:34

I get an error in ghci when I try to define a new type:

Prelude> data Point = Pt Int Int
:1:0: parse error on input `data\'
Prelude> let d         


        
相关标签:
4条回答
  • 2020-12-30 20:13

    ghci does not allow you to define types from interactive input - instead, you need to put your type definition in a file and :load the file into ghci.

    0 讨论(0)
  • 2020-12-30 20:17

    Just for historical reference, the HBI Haskell interactive environment allows for full Haskell at the command line, including types, classes and so on. There's no a priori GHCi can't operate similarly, and users could write a front-end to GHC-API that supported this...

    0 讨论(0)
  • 2020-12-30 20:18

    It is possible since GHC 7.4.1.

    0 讨论(0)
  • 2020-12-30 20:22

    titaniumdecoy, I remember being helped with this sort of GHCi mystery when I learned the frequently made point that writing things like 'let square x = x * x' inside the GHCi is like writing let a = f b with do notation in the IO monad -- say in this sort of example:

    palindromize :: IO ()
    palindromize = do
      a <- readFile "foo.txt"
      let b = reverse a
      putStrLn (a ++ b)
    

    Similarly, when you redefine an expression in the GHCi, it's sort of like doing the following in do notation, which is perfectly legitimate:

    makeMess :: IO ()
    makeMess = do
       a <- readFile "foo.txt"
       let b = reverse a
       putStrLn (a ++ b)
       let b = a
       putStrLn (a ++ b)
    

    No one would declare a data type in the middle of such a sequence, but would do it elsewhere in the module. I might have guessed that there was some sort of theoretical objection, but Don S.'s remark suggests there isn't one.

    0 讨论(0)
提交回复
热议问题