自己的数据类型“ Prelude.read:无解析”

时间:2019-05-16 14:04:48

标签: haskell haskell-prelude

我正在尝试从文件中读取两个自己的数据类型'BoardEdge'的列表。当我尝试运行代码时,出现异常:

  

“ Main.hs:Prelude.read:无解析”

我怀疑我在负责验证输入(validateInput)的函数上得到此信息。当我在ghci中尝试此功能时,插入两个BoardEdge'objects'效果很好,并给出True。

任何人都可以向我提供建议我做错了什么以及如何解决该问题?

数据类型:

data Field = Empty | Black | Yellow deriving (Eq, Ord, Enum, Show, Read)

data BoardEdge = BoardEdge { colRow :: [[(Field, Int)]]} deriving (Read, Eq, Ord, Show) 

Main.hs

    main :: IO()
    main = do
      args <- getArgs
      input <- loadInput args
      putStrLn "Puzzle input loaded:"
      putStrLn input
      let parsedInput = parseInput input
      if (validateInput parsedInput)
        then putStrLn "Input is valid."
        else error "Input invalid!"

    -- asks for path and reads input file
    loadInput :: [String] -> IO String
    loadInput [] =  getPath >>= readFile where
      getPath = do
        putStrLn "Provide path to puzzle input file:"
        getLine
    loadDefinition (a:_) = readFile a


    -- get valid data from input file
    parseInput :: String -> (B.BoardEdge,B.BoardEdge)
    parseInput d = parseInput' $ lines d where
      parseInput' (columns: rows :_) =
        (read columns, read rows)

Board.hs中导入的验证功能合格为B:

    validateInput :: (B.BoardEdge,B.BoardEdge) -> Bool
    validateInput (columns, rows) = rowColEq where
      rowColEq = countBlocks columns == countBlocks rows


    -- function that counts total quantity of colored blocks
    countBlocks :: (B.BoardEdge)-> Int
    countBlocks (B.BoardEdge colRow) = countBlocks' $ concat colRow where
      countBlocks' [] = 0
      countBlocks' (x:xs) = snd x + countBlocks' xs

我的输入文件如下:

    [[(Black,2),(Yellow,2),(Black,1)],[(Black,2),(Yellow,1),(Black,3)]]
    [[(Black,5)],[(Black,2),(Black,1)],[(Black,2),(Black,2)],[(Black,1),(Black,2)]]

1 个答案:

答案 0 :(得分:1)

将您自己的代码段和Fyodor的注释结合在一起:

Prelude> data Field = Empty | Black | Yellow deriving (Eq, Ord, Enum, Show, Read)
Prelude> data BoardEdge = BoardEdge { colRow :: [[(Field, Int)]]} deriving (Read, Eq, Ord, Show)
Prelude> let edge1 = BoardEdge [[(Black,2),(Yellow,2),(Black,1)],[(Black,2),(Yellow,1),(Black,3)]]
Prelude> show edge1
"BoardEdge {colRow = [[(Black,2),(Yellow,2),(Black,1)],[(Black,2),(Yellow,1),(Black,3)]]}"
Prelude> let correctInput = it -- ^^ the above

因此,现在我们知道read的期望,即show的期望。与您用作输入的内容相比如何?

Prelude> let myInput =     "[[(Black,2),(Yellow,2),(Black,1)],[(Black,2),(Yellow,1),(Black,3)]]"
Prelude> correctInput == myInput
False

或更狡猾:如果您希望默认的read实例解析您的输入,则您的输入必须是正确的具有数据构造函数和全部的Haskell代码。在这种情况下,需要使用BoardEdge