我有一个包含姓名,月,日的3元组的出生记录列表。我想添加新的元组并显示birthBook。但是,在我添加或删除值后,birthBook不会更改 比如,我添加了tom 5 6但是打印birthBook只显示“dd”4 5,这意味着(tom,5,6)不会在birthBook中添加。我该怎么办? 这是我的代码:
birthBook::[(String,String,String)]
birthBook=[("dd","4","5")]
prompt :: String -> IO ()
prompt todos = do
putStrLn "Enter a command(add,remove,print)"
cmd <- getLine
interpret cmd todos
interpret :: String->String-> IO ()
interpret "print" todos= do
print(birthBook)
prompt todos
interpret "add" todos= do
putStrLn "Enter a name"
cmdname<-getLine
putStrLn "Enter an integer month"
cmdmonth<-getLine
putStrLn "Enter an integer day"
cmdday<-getLine
print(add birthBook cmdname cmdmonth cmdday)
prompt todos
add::(Eq key)=>[(key,v,z)]->key->v->z->[(key,v,z)]
add birthBook name month day = (name, month, day):birthBook
main= prompt []
答案 0 :(得分:2)
这里的问题是你忘了Haskell纯粹是功能性的,并且默认情况下不会将值视为可变。
您需要将出生簿作为参数传递给prompt
和interpret
,以便保持任何更改。您还尝试打印birthBook
的初始声明,它始终保持相同,因为Haskell是一种纯函数式编程语言,如果您想要更改任何内容,则需要创建数据的新副本以及您希望进行的所需更改 - 因此我在您的解释例程结束时放置了let newBirthBook
表达式。
{-# LANGUAGE OverloadedStrings #-}
module Main where
birthBook::[(String,String,String)]
birthBook=[("dd","4","5")]
prompt :: [(String,String,String)] -> String -> IO ()
prompt bBook todos = do
putStrLn "Enter a command(add,remove,print)"
cmd <- getLine
interpret bBook cmd todos
interpret :: [(String,String,String)] -> String -> String -> IO ()
interpret bBook "print" todos = do
print bBook
prompt bBook todos
interpret bBook "add" todos = do
putStrLn "Enter a name"
cmdname<-getLine
putStrLn "Enter an integer month"
cmdmonth<-getLine
putStrLn "Enter an integer day"
cmdday<-getLine
let newBirthBook = add bBook cmdname cmdmonth cmdday
prompt newBirthBook todos
add :: (Eq key) => [(key,v,z)] -> key -> v -> z -> [(key,v,z)]
add birthBook name month day = (name, month, day):birthBook
main= prompt birthBook []