2017-04-02 62 views
0

中在数据表现得那么在这个节目,我有一个自定义的数据类型,Msg这是一个C Char远。在程序中,创建一个单独的线程和一个单独的函数userThread监听键击,并存储在一个MVar发送的炭即充当了mainuserThread并发哈斯克尔:自定义数据类型

我已经得到的点之间的简单的通信信道,使用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] 

我怎样才能让我的消息适应这个列表?非常感谢您的帮助。

+0

'C R < - takeMVar chan' – melpomene

+0

谢谢您的回复,但我仍然有型的问题。在让Haskell自己将'Msg'打印为字符后,我尝试将它添加到一个新的空列表中* *不能与IO类型[]匹配IO 预期类型:IO字符 实际类型:[Char]' –

回答

0

问题接缝是你的列表中不包含C Char而是Char。这可以通过做let x = [C '1',C 's',C 'g',C '4',C '5']来解决。

userThread把一个C Charchan,所以当你与takeMVar (chan)解压并将其绑定到rr现在有型Msg。由于Haskell中的列表只能容纳相同类型的值,你不能在前面加上一个Msg[Char],为此错误。使Msgx所有要素,都将是不错的(希望...)。或者你可以实现一个

toChar :: Msg -> Char toChar C c = c

,并完成类似(toChar r):x如果你坚持在列表中有Char

用于remvoing从x中看到this元件。你可以写一些这样的东西:

if elem r x then newX = remove r x else newX = r:x --if x contains Msg 
if elem cr x then newX = remove cr x else newX = cr:x 
    where cr = toChar r --if you insist on having chars in x... 

希望有所帮助。

+0

撇开:如果您不满意'deriving(Show)'代表您的'Msg'的方式,您可以通过提供您自己的show实现来使'Msg'成为'Show'类型实例的实例,如下所示:'instance Show Msg where <你的show>的实现。 – Chris