我还在学习Haskell,而且我正在做一些练习,但是我很伤心.所以我有一个名为"novel"的函数,它需要2个字符串和一个Int(novel :: (String, String, Int) -> String,它的参数).Novel的输入/输出必须如下所示:
> novel ("Rowling", "Harry Potter", 1998)
"Harry Potter (Rowling, 1998)"
Run Code Online (Sandbox Code Playgroud)
这是我的新功能的代码,如上所述:
novel :: (String, String, Int) -> String
novel (author, book, year) = book ++ " (" ++ author ++ ", " ++ (show year) ++ ")"
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个名为"cite"(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)"
Run Code Online (Sandbox Code Playgroud)
我试图递归地使用"小说",以获得所需的输出,但我不知道如何去做.
我尝试过的:
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))]
Run Code Online (Sandbox Code Playgroud)
老实说,就我而言.显然,它不起作用,但我不知道该怎么做.
也许这会给你一个良好的开端:
cite :: [(String, String, Int)] -> String
cite [] = ""
cite (x:xs) = undefined -- put your code that recursively calls cite in here, hint: use ++ and "\n\"
Run Code Online (Sandbox Code Playgroud)
模式匹配(x:xs)说明了这一点,给我列表中的第一项和列表x的尾部xs.这与写这个是一样的:
cite xs' = let x = head xs'
xs = tail xs'
in undefined -- your code here
Run Code Online (Sandbox Code Playgroud)
甚至
cite xs' = undefined -- your code here
where
x = head xs'
xs = tail xs'
Run Code Online (Sandbox Code Playgroud)
希望这有助于推动您朝着正确的方向前进.
编辑:OP询问如何递归执行此操作,下面是我原来的答案:
你可能应该重写你的基础案例cite [] = "".它并没有真正有所作为,但它有助于代码可读性.
让我们首先将":t map novel"放入ghci,看看你得到了什么:
> :t map novel
map novel :: [([Char], [Char], Int)] -> [[Char]]
Run Code Online (Sandbox Code Playgroud)
我们可以改写为: map novel :: [(String, String, Int)] -> [String]
怎么样?因为map将一种类型转换a为另一种类型b并将其应用于列表中的每个项目.第一个参数map是任何带有一个参数的函数.究竟是什么呢novel.
但这并没有给我们你需要的东西,我们最终会得到一个字符串列表而不是字符串:
> cite [("author1", "book1", year1), ("author2", "book2", year2), ("author3", "book3", year3)]
["book1 (author1, year1)","book2 (author2, year2)","book3 (author3, year3)"]
Run Code Online (Sandbox Code Playgroud)
并且您希望它是由换行符"\n"分隔的单个字符串.是否有一个函数可以获取字符串列表并将它们连接成一个字符串,但插入它们之间的分隔符?
首先让我们描述一下这样一个功能:String -> [String] -> String.接下来我们把它扔进Hoogle看看我们得到了什么:https://www.haskell.org/hoogle/ ?hoogle = String + - %3E+%5BString%5D+-%3E+String
啊,第二个功能intercalate听起来像我们需要的.它不仅适用于字符串,它适用于任何列表.它会如何工作?像这样的东西:
> import Data.List (intercalate)
> intercalate "\n" ["List","Of","Strings"]
"List\nOf\nStrings"
Run Code Online (Sandbox Code Playgroud)
所以现在你可以结合插入和映射来获得你想要的东西.我将保留cite给你的定义.
编辑:完全忘了,实际上有一个专门的功能.如果您只是[String] -> String在Hoogle中搜索,您会发现unlines
| 归档时间: |
|
| 查看次数: |
201 次 |
| 最近记录: |