我正在尝试阅读文件。标题被正确阅读,但当我尝试阅读演员(演员)时,它似乎并没有停下来搜索这一年。在解析Actors或解析Chars时有错误吗?
-- Types
type Title = String
type Actor = String
type Cast = [Actor]
type Year = Int
type Fan = String
type Fans = [Fan]
type Period = (Year, Year)
type Database = [Film]
type Film = (Title, Cast, Year, Fans)
- 用于读取文件的解析方法
parseLines :: [String] -> Film
parseLines list = (list !! 0, parseActors (drop 1 list), read(list !! 2), parseActors (drop 3 list))
parseFans :: [String] -> Fans
parseFans [] = []
parseFans list
| length list > 0 = [(list !! 0)] ++ parseFans (drop 1 list)
parseActors :: [String] -> Cast
parseActors [] = []
parseActors list
| length list > 0 = [(list !! 0)] ++ parseActors (drop 1 list)
parseChars :: String -> String -> [String]
parseChars [] _ = []
parseChars (x:xs) stringCount
| x == ',' = [stringCount] ++ parseChars xs ""
| otherwise = (parseChars xs (stringCount ++ [x]))
parseAll :: [String] -> [Film]
parseAll [] = []
parseAll (x:xs) = parseLines (parseChars x "") : (parseAll xs)
我收到此错误
|枪手| | Idris Elba,Sean Penn,Javier 巴登,2015年,加里,戴夫,佐伊,凯文| | *主> ***例外: Prelude.read:没有解析
这是我的文本文件
The Gunman,Idris Elba,Sean Penn,Javier Bardem,2015,Garry,Dave,Zoe,Kevin,Emma,
The Shawshank Redemption, Tim Robbins, Morgan Freeman, Bob Gunton, 1994, Bill, Jo, Garry, Kevin, Olga, Liz,
The Dark Knight, Christian Bale, Heath Ledger,Aaron Eckhart, 2008, Zoe, Heidi, Jo, Emma, Liz, Sam, Olga, Kevin, Tim,
Inception, Leonardo DiCaprio, Ellen Page, 2010, Jo, Emma, Zack, Olga, Kevin,
答案 0 :(得分:1)
parseActors :: [String] -> Cast
parseActors [] = []
parseActors list
| length list > 0 = [(list !! 0)] ++ parseActors (drop 1 list)
你试过这个看看它做了什么吗?
ghci> parseActors ["one", "two", "three"]
["one", "two", "three"]
你所做的是写了一个过于复杂的版本:
parseActors :: [String] -> Cast
parseActors list = list
同样地,
parseFans :: [String] -> Fans
parseFans [] = []
parseFans list
| length list > 0 = [(list !! 0)] ++ parseFans (drop 1 list)
此代码与parseActors
相同,您只需将名称更改为parseFans
,将结果类型更改为Fans
。其行为与:
parseFans :: [String] -> Fans
parseFans list = list
我现在要继续忽略上述内容。让我们以parseChars
代替旋转。
ghci> parseChars "one,two,three," ""
["one", "two", "three"]
啊,一个实际解析的函数。我不确定你是如何期待这个工作的,但我认为它正如预期的那样工作。
我想提请你注意parseLines的这一部分:
read(list !! 2)
这是您用来尝试提取年份的内容。这就是抛出错误:Prelude.read: no parse
。请注意它如何告诉您使用Prelude.read
是罪魁祸首。
好。让我们拍摄第一部电影并运行一些代码。
ghci> let gunman = "The Gunman,Idris Elba,Sean Penn,Javier Bardem,2015,Garry,Dave,Zoe,Kevin,Emma,"
ghci> let list = parseChars gunman ""
ghci> list
["The Gunman","Idris Elba","Sean Penn","Javier Bardem","2015","Garry","Dave","Zoe","Kevin","Emma"]
ghci> list !! 2
"Sean Penn"
请注意list !! 2
不是年份。这是你的问题。嗯,其中一个,无论如何。
希望能吸取教训: