2016-03-09 161 views
0

你好我想這個字符串將字符串轉換爲自定義類型的Haskell

Blade Runner,Ridley Scott,1982,Amy,5,Bill,8,Ian,7,Kevin,9,Emma,4,Sam,7,Megan,4​ 

轉換爲電影類型

type UserRatings = (String,Int) 
type Film = (Title, Director, Year , [UserRatings]) 

從包含25部電影

這個文本文件是我試圖做的

maybeReadTup :: String ->(String, Int) 
maybeReadTup s = do 
    [(n, [c])] <- return $ reads s 
    return [(n, [c])] 

    parseLines :: [String] -> Film 
    parseLines list 
      | isInt(list !! 3) = (list !! 0,(list !! 1), read (list !! 2), maybeReadTup [ (list!!1,read (list !! 2))]) 

isInt :: String ->Bool 
isInt[] = True 
isInt (x:xs) 
    | isNumber x = True && isInt xs 
    | otherwise = False 

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) 

但我得到錯誤的類型可以有人請幫我解析這個UserRatings元組類型[(String,Int)]?你能幫我理解parseLines的工作原理嗎?我在Haskell

+0

爲什麼在輸入每一個字,用逗號隔開? – chepner

+0

@chepner有沒有更好的方法來做到這一點?如果我改變這個文件,它會幫助我解析它嗎? – Max

+0

我想象一下像'Blade Runner,Ridley Scott,1982,...'這樣的東西會更好,這樣你就可以知道標題結尾和導演開始的位置(當然,假設標題不包含逗號)。 – chepner

回答

2

這裏新是一個使用Text.Parsec一個解決方案:

import   Text.Parsec 
import   Text.Parsec.String 

type UserRatings = (String, Int) 
type Title = String 
type Director = String 
type Year = Int 
type Film = (Title, Director, Year, [UserRatings]) 

str :: Parser String 
str = many1 (noneOf ",") 

int :: Parser Int 
int = read <$> many1 digit 

tup :: Parser UserRatings 
tup = do user <- str 
     _ <- oneOf "," 
     rating <- int 
     return (user, rating) 

parser :: Parser Film 
parser = do title <- str 
      _ <- oneOf "," 
      director <- str 
      _ <- oneOf "," 
      year <- int 
      _ <- oneOf "," 
      ratings <- sepBy tup (oneOf ",") 
      eof 
      return (title, director, year, ratings) 

testString :: String 
testString = "Blade Runner,Ridley Scott,1982,Amy,5,Bill,8,Ian,7,Kevin,9,Emma,4,Sam,7,Megan,4" 

main :: IO() 
main = print $ runParser parser() "testString" testString 
+0

我有一個數據庫,所以「testString」對我來說沒用,我怎樣才能修復這裏的代碼來把我的數據庫放在解析器中? '主:: IO() 主要=不 tempDatabase < - READFILE 「films.txt」 讓我=行tempDatabase 讓數據庫= runParser解析器()數據庫 putStrLn 「輸入您的姓名:」 用戶名< - 函數getline userInterface數據庫用戶名 appendFile「films.txt」(顯示數據庫) putStrLn「您對數據庫的更改已成功保存。」 – Max

+0

調用數據庫的文本文件有點誇張。 'filmList < - map(runParser parser()fileName)<$> lines <$> readFile fileName' should be working。 – obadz

相關問題