中在数据表现得那么在这个节目,我有一个自定义的数据类型,Msg
这是一个C Char
远。在程序中,创建一个单独的线程和一个单独的函数userThread
监听键击,并存储在一个MVar
发送的炭即充当了main
和userThread
并发哈斯克尔:自定义数据类型
我已经得到的点之间的简单的通信信道,使用deriving (Show)
在那里我可以打印Msg作为终端,就像一个字符串。如果用户键入j
输出为:
C 'j'
(请注意,也打印C使用时我只希望焦炭本身)
我有一个现成的名单,我的目标是,如果char是不是在列表,然后添加它。如果是,那么不要添加它并删除列表中所有字符的实例。
例如,如果用户键入c
,然后
[a,b] becomes [a,b,c]
但
[f,c,c,h,c] becomes [f,h]
我当前的代码如下:
module Main where
import Control.Concurrent
import Control.Monad
import System.IO
import System.Random
import Text.Printf
data Msg = C Char deriving (Show)
main :: IO()
main = loop
where
loop = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
--already existing list
let x = [1, 's', 'g', 4 ,5]
chan <- newEmptyMVar
forkIO $ userThread (chan)
r <- takeMVar (chan)
putStrLn $ show x
print r
-- Listens for keystrokes from the user, the passes them to the main thread
userThread :: MVar Msg -> IO()
userThread chan = do
c <- getChar
putMVar chan (C c)
我很困惑,我能够执行像打印在我的Msg
上的操作就好,因为它的实际内容是字符。但是,当我尝试广告时,它使用r:x
编译错误列表,说:
* Couldn't match type `Char' with `Msg'
Expected type: [Msg]
Actual type: [Char]
我怎样才能让我的消息适应这个列表?非常感谢您的帮助。
'C R < - takeMVar chan' – melpomene
谢谢您的回复,但我仍然有型的问题。在让Haskell自己将'Msg'打印为字符后,我尝试将它添加到一个新的空列表中* *不能与IO类型[]匹配IO 预期类型:IO字符 实际类型:[Char]' –