首页 > 解决方案 > 无法将类型与 Maybe b0 匹配

问题描述

您好我遇到以下问题:我定义了一个类型类:

类型类

class TextEncode  a where
        toText::a->Text
        fromText::Text->a

我想解析一个TCPFile

data TCPFile=Rfile (Maybe Readme) | Dfile  Samples | Empty 

我不会显示SamplesandReadme类型,因为在这种情况下它们无关紧要。我正在尝试使用该fromText方法来获取TCPFile.

类型

data FileData=FileData{ header::Header,rawContent::Text}

data Header=Header { ftype::Char}

FileData用于存储文件和将Header被解析的内容:

我正在使用我Functor定义的链接操作:

(>>?)::Maybe a->(a->Maybe b)->Maybe b
    (Just t) >>? f=f t
    Nothing >>? _=Nothing

代码

instance TextEncode TCPFile where
        fromText txt = readHeader txt >>? (\h -> Just (FileData h txt)) >>? makeFile


    readHeader::Text->Maybe Header
    readHeader txt=case Data.Text.head txt of 
        'r' ->Just (Header{ ftype='r'})
        'd' ->Just (Header {ftype ='d'})
        _  ->Nothing



    makeFile::FileData->TCPFile
    makeFile fd= case ftype.header $ fd of
            'r'->Rfile (Just (fromText . rawContent $ fd))
            'd'->Dfile (fromText . rawContent $ fd)
            _  ->Empty 

我在方法中不断收到这个错误,makeFile我不明白为什么。我放的是makeFile一个Maybe FileData,通过>>?.TCPFileTextEncode typeclass

错误

  TCPFile.hs:59:24: error:
        * Couldn't match expected type `TCPFile'
                      with actual type `Maybe b0'
        * In the expression:
            readHeader txt >>? (\ h -> Just (FileData h txt)) >>? makeFile
          In an equation for `fromText':
              fromText txt
                = readHeader txt >>? (\ h -> Just (FileData h txt)) >>? makeFile
          In the instance declaration for `TextEncode TCPFile'
       |
    59 |         fromText txt = readHeader txt >>? (\h -> Just (FileData h txt)) >>? makeFile

       |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

^^^

标签: haskelltypeclassfunctor

解决方案


推荐阅读