我是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)发布于 2016-07-02 17:17:42
对于该任务,使用read是非常可怕的,只需使用构造函数Contact即可。
fromDt :: [String] -> ContactInfo
fromDt [n,s,m] = Contact n s m请注意,如果您传递给fromDt的列表长度不是3个单元格,您仍然会得到一个错误。我会简单地避免定义这个脆弱的函数,并在调用fromDt的任何地方直接使用构造函数Contact。
发布于 2016-07-02 17:24:50
当您使用record语法定义数据类型时,派生的读取实例需要完整的record语法-即,您必须传递如下字符串
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 }"https://stackoverflow.com/questions/38157966
复制相似问题