***例外:Prelude.read:没有解析

时间:2016-07-02 08:06:49

标签: haskell

我是Haskell的新手,我写了这个小脚本,但我读到了这个:没有解析异常,有人可以帮我吗? 感谢

import System.Environment
import Data.List

data ContactInfo = Contact { name :: String
                        , surname :: String
                        , mobile :: String
                        } deriving (Read, Show)

fromDt :: [String] -> ContactInfo
fromDt ds = read $ "Contact " ++ (Data.List.concat $ Data.List.intersperse " " $ Data.List.map show ds)

main = do
  let val =  fromDt ["John","Smith","223 455 2703"]
  putStrLn ("Name: " ++ name val ++ ", " ++ surname val)

2 个答案:

答案 0 :(得分:5)

使用read对于该任务来说非常糟糕,只需使用构造函数Contact

fromDt :: [String] -> ContactInfo
fromDt [n,s,m] = Contact n s m

请注意,如果传递给fromDt的列表长度不是3个单元格,则仍会出现错误。我只是避免定义这个脆弱的函数,并直接使用构造函数Contact,无论你在哪里调用fromDt

答案 1 :(得分:2)

使用记录语法定义数据类型时,派生的读取实例需要完整的记录语法 - 即您必须传递一个字符串,如

ContactInfo { name = "...", surname = "...", mobile = "..." }

read获取ContactInfo值。字符串如:

ContactInfo "..." "..." "..."

将导致无解析异常。这是一个快速演示:

data ABC = ABC { a :: Int, b :: Int, c :: Int }
  deriving (Show, Read)

test1 :: ABC                  -- throws no parse exception
test1 = read "ABC 1 2 3"

test2 :: ABC                  -- works
test2 = read "ABC { a = 1, b = 2, c = 3 }"