如何使用Haskell数据类型创建?

时间:2018-04-17 03:07:45

标签: haskell

我是Haskell的新编程。我试图打印我的新数据类型但不起作用。我在Geany做这个,制作一个主要的。

module Main (
main
) where

import Graphics.UI.Gtk
--import Control.Monad.ST
import Data.IORef


--main::IO ()
main = do
 pila <- newIORef (Pila[])

 let x = apilar 1 pila
 putStrLn x

 mainGUI


-------------------------


data Pila x = Pila[x] deriving (Show)

pila_vacia :: Pila x
pila_vacia = Pila[]

apilar :: x -> Pila x -> Pila x
apilar e (Pila lista) = Pila([e] ++ lista)

来自终端的错误:参数可能有问题

[1 of 1] Compiling Main( Pilas.hs, Pilas.o )

Pilas.hs:14:19:
    Couldn't match expected type ‘Pila x’
                with actual type ‘IORef (Pila x0)’
    Relevant bindings include
      x :: Pila x (bound at Pilas.hs:14:6)
      pila :: IORef (Pila x0) (bound at Pilas.hs:12:2)
    In the second argument of ‘apilar’, namely ‘pila’
    In the expression: apilar 1 pila

Pilas.hs:15:11:
    Couldn't match type ‘Pila x1’ with ‘[Char]’
    Expected type: String
      Actual type: Pila x1
    In the first argument of ‘putStrLn’, namely ‘x’
    In a stmt of a 'do' block: putStrLn x

抱歉我的英文不好

1 个答案:

答案 0 :(得分:4)

问题是,pila不是Pila x类型,正如您显然所期望的那样,但类型为IORef (Pila x)。这就是the function newIORef所做的 - 它会创建一个新的IORef

要从Pila中获取IORef值,请使用the readIORef function,如下所示:

main = do 
    pilaRef <- newIORef (Pila[]) 

    pila <- readIORef pilaRef
    let x = apilar 1 pila 
    ...