首页 文章

在Haskell中创建字符串列表

提问于
浏览
2

我正在从Java到Haskell朝圣 . 从广义上讲,我得到了Haskell背后的主要概念 . 阅读所有教程和书籍是有道理的,但我从头开始编写自己的代码 .

我想在文件系统上创建1000个带有名称的文件

“myfile_1.txt”...“myfile_1000.txt”

每个都包含一些虚拟文本 .

到目前为止,我已经完成了整个IO的事情,并意识到我需要构建一个长度为1000的字符串列表 . 所以我有:

buildNamesList :: [] -> []
buildNamesList ???

一旦我有了List,我就可以在每个元素上调用writefile方法 . 我无法弄清楚的是如何在String的末尾添加一个数字来获取每个fileName因为我不能有一个int i = 0,我在Haskell中构造 .

我在这里有点超出我的深度,会感谢一些指导,谢谢

4 回答

  • 7

    一种可能的方案:

    buildNamesList = map buildName [1..1000]
      where buildName n = "myfile_" ++ show n ++ ".txt"
    
  • 0
    import Control.Applicative
    
    fileNames = ("myFile_"++) <$> (++".txt")  <$> show <$> [1..1000]
    
  • 5

    然后如何遍历它,在元素n处取出String然后将其传递给另一个函数?

    没有! "Plucking out"列表中的某些内容效率低下 . 你必须使用命令式语言,因为它们只是在语言中构建了一些神奇的东西 . Haskell有much more well-specified, mathematically sound and type-safe magic for that;因此,你不需要循环等 .

    您知道如何处理每个元素( String -> IO () ),并且您知道数据来自何处( [String] ) . 你也知道最终会发生什么( IO () ) . 所以您正在寻找的组合器类型为 ( String -> IO() ) -> [String] -> IO () ,但显然它没有't really depend on the data being Strings, so let'将其简化为 (a -> IO()) -> [a] -> IO() . 你可以look that up on Hoogle,它提供sume垃圾 mapM_forM_ ,两者都做你想要的:

    mapM_ (\filename -> writeFile filename "bla") filenamesList
    

    要么

    forM_ filenamesList $ \filename ->
       writeFile filename "bla"
    
  • 2

    有时我认为 foldrfor 循环有一些相似之处 . 这里有点像 i++ 构造,在循环中应用 i

    foldr (\i accum -> ("myfile_" ++ show i ++ ".txt") : accum) [] [1..1000]
    

    另一种方法可能是 zipWith ,它应用一个函数来组合两个列表:

    zipWith (\a b -> a ++ show b ++ ".txt") (repeat "myfile_") [1..1000]
    

    要么

    zipWith ($) (repeat (("myfile_" ++) . (++ ".txt") . show)) [1..1000]
    

    这里也是一个递归的例子,应用为 fileList "myfile_" ".txt" [1..1000]

    fileList _     _   []     = [] 
    fileList fName ext (x:xs) = (fName ++ show x ++ ext) : fileList fName ext xs
    

相关问题