好的,经过一晚的工作,我得到了这些代码部分,这些部分一直给我带来问题。首先,我想道歉,你们中的很多人都会认为这是愚蠢的错误。
第一部分是convertToHTML -
convertToHTML :: String -> String
convertToHTML [] = [] --prevents calling head on empty line
convertToHTML x --here is where I know I'm missing something.
| x == "---" = "<hr/>" --this works!
| doubleHashes x == "True" = "<h2>" ++ x ++ "</h2>" --also wrong
| doubleHashes x == "False" = "<h1>" ++ x ++ "</h1>" --also wrong
| otherwise = x然而,convertToHTML的代码工作得很好..。
convertToHTML' :: String -> String
convertToHTML' = unlines.map (convertToHTML.escapeChars).lines现在转到escapeChar部分。这让我犯了一个不匹配类型的错误,这是从下面的裸露x中得到的。我是否在代码的前面将x声明为变量,以便在这里调用它?
escapeChar :: Char -> String
escapeChar '&' = "&"
escapeChar '<' = "<"
escapeChar x = x以及调用函数的escapeChars
escapeChars :: String -> String
escapeChars = concatMap escapeChar最后,doubleHashes助手函数..。
doubleHashes ('#' : '#' : []) = True
doubleHashes _ _ = False --different amounts of arguments.然而,我的主要方法是完美地工作!其中,我从读取输入文件中获取内容,最后调用:
writeFile outFile $ convertToHTML' $ contents我知道我错过了一些简单的代码,但我就是搞不懂.谢谢
发布于 2014-12-04 14:52:11
&和>的代码是错误的:它只在第一个位置替换,而应该在任何地方替换。它应该在#替换之前而不是之后替换,所以如果您有## foo > bar,那么它将被正确地处理。
escapeChars :: String -> String
escapeChars = concatMap escapeChar
escapeChar :: Char -> String
escapeChar '&' = "&"
escapeChar '>' = ">"
escapeChar x = [x]只需用escapeChars编写convertToHtml
convertToHTML' :: String -> String
convertToHTML' = unlines.map (convertToHTML . escapeChars).lines如果不需要处理###,那么要处理##,就可以编写带有模式匹配的助手函数:
doubleHashes ('#' : '#' : []) = True
doubleHashes _ = False另外,您的h1生成器将#留在标记中。
convertToHTML :: String -> String
convertToHTML [] = [] --prevents calling head on empty line
convertToHTML x
| head x == '#' = "<h1>" ++ tail x ++ "</h1>"
| doubleHashes x = "<h2>" ++ drop 2 x ++ "</h2>"
| x == "---" = "<hr/>"
| otherwise = x发布于 2014-12-04 11:58:14
使用span
Prelude> let s1 = "# one"
Prelude> let s2 = "## two"
Prelude> let (hashes, content) = span (== '#') s1
Prelude> hashes
"#"
Prelude> content
" one"
Prelude> "<h" ++ (show $ length hashes) ++ ">" ++ content ++ "</h" ++ (show $ length hashes) ++ ">"
"<h1> one</h1>"
Prelude> let (hashes, content) = span (== '#') s2
Prelude> "<h" ++ (show $ length hashes) ++ ">" ++ content ++ "</h" ++ (show $ length hashes) ++ ">"
"<h2> two</h2>"实际上,应该在convertToHTML上递归地调用content。
https://stackoverflow.com/questions/27293306
复制相似问题