【问题标题】:Haskell Reading lines from File and print these with modificationsHaskell 从文件中读取行并进行修改打印
【发布时间】:2021-04-24 10:45:11
【问题描述】:

我想读取每行包含一个单词的文件并逐行打印该文件,并在行尾添加单词的长度。

到目前为止,我得到了这个解决方案,它消除了类型不匹配的错误。

我已经尝试了几天,但我完全失去了信心。我无法理解 Haskell。

我希望有人可以帮助我。

这是我的代码:

import System.IO


main :: IO ()
main = do

  file <- readFile "palindrom.txt"
  putStrLn (unlines $ showLength $ lines file)

showLength (x:xs) = (x concat "has length of" length x) (showLength xs)

【问题讨论】:

    标签: haskell io


    【解决方案1】:

    改成

    showLength :: [[Char]] -> [[Char]]
    showLength (x:xs) = -- (x concat "has length of" length x) (showLength xs)
                concat [x, " has length of ", show (length x)] : showLength xs
    showLength  []  =  []
    

    它会起作用的。您的原始代码在 Haskell 中没有多大意义。

    concat :: [[a]] -&gt; [a] 是一个内置函数,它将给定列表中的所有列表连接在一起:

    > concat [[1],[2,3],[4]]
    [1,2,3,4]
    
    > concat ["a"," b ", "123"]
    "a b 123"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      相关资源
      最近更新 更多