【发布时间】:2015-01-11 22:00:46
【问题描述】:
我还在学习 Haskell,我正在做一些练习,但我遇到了麻烦。所以我有一个名为“novel”的函数,它需要 2 个字符串和一个 Int
(novel :: (String, String, Int) -> String) 的论点。 Novel 的输入/输出必须如下所示:
> novel ("Rowling", "Harry Potter", 1998)
"Harry Potter (Rowling, 1998)"
这是我的新颖功能的代码,如上所述:
novel :: (String, String, Int) -> String
novel (author, book, year) = book ++ " (" ++ author ++ ", " ++ (show year) ++ ")"
我正在尝试编写一个名为“引用”(cite :: [(String, String, Int)] -> String) 的新函数。 Cite 的输入/输出应如下所示:
> cite [("author1", "book1", year1), ("author2", "book2", year2), ("author3", "book3", year3)]
"book1 (author1, year1)
book2 (author2, year2)
book3 (author3, year3)"
我正在尝试递归地使用“新颖”,以获得所需的输出,但我不知道如何去做。
我尝试过的:
cite :: [(String, String, Int)] -> String -- | Listed arguments
cite [] = "" -- | Base Case
cite x:xs = [(novel (author, book, year)), (novel (author, book, year)), (novel (author, book, year))]
老实说,据我所知。显然,它不起作用,但我不确定从这里开始做什么。
【问题讨论】:
-
提示:查看
map的想法。 -
您希望它返回在每次引用之间使用“\n”的
String(即[Char]),还是返回[String]? -
我不明白 map 在这里对我有什么帮助。我对 map 的理解是它需要一个函数和一个列表,您可以使用算术运算来操作该列表中的项目。
-
@TheCriticalImperitive 我没有返回列表。我正在返回一个字符串。它的返回方式与小说返回的方式相同。
-
@JoffreyBaratheon
map可以对列表项执行任何操作,而不仅仅是算术。String与 Haskell 中的Chars 列表相同。事实上,String类型只是[Char]的同义词。