返回 Haskell 中字符串的第一行



>我有一个相当简单的问题,我被难住了。基本上,我只需要编写一个函数,该函数获取一个字符串,将其分成几行,获取第一行并以正确格式的 HTML 标题标签返回第一行。

老实说,我只是不知道从哪里开始。

任何事情都会有所帮助。

确实有代码,但这只是我用来对输入文件进行转换的一些基本函数:

    convertToHTML :: String -> String
    convertToHTML cs0 = 
          case cs0 of
                ('#' : '#' : cs) -> "<h2>" ++ cs ++ "</h2>"
                ('#' : cs)       -> "<h1>" ++ cs ++ "</h1>"
                 "---"            -> "<hr/>"
                  _                -> cs0
    convertToHTML' :: String -> String
    convertToHTML' = unlines.map (convertToHTML.firstLine.escapeChars).lines
    convertToWords :: String -> String
    convertToWords cs1 =
                case cs1 of
                      ('*' : '*' : cs) -> "<strong>" ++ cs ++ "</strong>"
                      ('_' : '_' : cs) -> "<strong>" ++ cs ++ "</strong>"
                      ('*' : cs)       -> "<em>" ++ init cs ++ "</em>"
                      ('_' : cs)       -> "<em>" ++ init cs ++ "</em>"
                      _                -> cs1
    convertToWords' :: String -> String
    convertToWords' = unwords.map convertToWords.words

这些是我从 main 调用的基本函数,它读取输入文件、调用函数并生成输出文件。

    main = do
          args <- getArgs -- command line args
          let (infile,outfile) = ((x:y:ys)->(x,y)) args
          putStrLn $ "Input file:  " ++ infile
          putStrLn $ "Output file: " ++ outfile
          contents <- readFile infile      
          writeFile outfile $ deleteSymbol $ convertToWords' $ convertToHTML' $ contents

希望您了解代码的要点。

要检索第一行,您只需使用:

firstLine :: String -> String
firstLine = head . lines

然后,您可以使用:

firstLineInTitleTags :: String -> String
firstLineInTitleTags s = concat ["<title>", firstLine s, "</title>"]

或:

firstLineInTitleTags :: String -> String
firstLineInTitleTags = ("<title>"++) . (++"</title>") . firstLine