【问题标题】:Haskell combining values into string using show, recursivlyHaskell 使用 show 递归地将值组合成字符串
【发布时间】:2015-04-26 18:12:09
【问题描述】:
writer :: DataBase -> IO ()
writer [] = writeFile "output.txt" ""
writer xs = writeFile "output.txt"  (createOutput xs)

createOutput :: DataBase -> String
createOutput [] = ""
createOutput (x:xs) = (show (get1 x)++", "++ (get2 x)++", "++(get3 x)++", "++show(get4 x) ++", "++show(get5 x)++", "++show(get6 x)++"\n") : createOutput xs

createOutput结束时的递归调用

 : createOutput xs

破坏了我的功能,它可以在没有递归的情况下正常工作,但我无法递归执行它,这是重点。我要做的是从“自定义”数据类型中获取值,该数据类型基本上是元组列表和get1get2 等,获取元组中的第一秒等元素

type Id = Integer
type Song = String
type Group = String
type Year = Integer
type Length = Integer
type Rate = Rational

type Data = (Id, Song, Group, Year, Length, Rate)
type DataBase = [Data]
get1 (a1, _, _, _, _, _) = a1
get2 (_, a2, _, _, _, _) = a2
get3 (_, _, a3, _, _, _) = a3
get4 (_, _, _, a4, _, _) = a4
get5 (_, _, _, _, a5, _) = a5
get6 (_, _, _, _, _, a6) = a6

我正在使用show 将非字符串变量转换为字符串,但是当我尝试让函数自递归调用它时,一切都崩溃了,我尝试在周围添加一堆括号,或者不使用show,但是即便如此,只需单个 get 声明它就会崩溃,老实说它让我无法理解为什么......

我知道我可以使用writeFile "output.txt" (show xs) 打印文件,但它不会产生我想要的输出,每个元组都没有引号和换行

【问题讨论】:

    标签: string haskell file-io recursion


    【解决方案1】:

    您似乎需要在 createOutput 递归调用结束时再次使用附加 (++) 而不是 cons (:)。

    想想类型,++ 连接两个Strings(正式等于CharsLists),而: 在字符串的开头添加一个Char

    这可以通过它们的类型签名更正式地识别:

    (++) :: [a] -> [a] -> [a]
    (:) :: a -> [a] -> [a]
    

    【讨论】:

    • 干杯它有效,不确定我是否应该为它如此简单而感到愚蠢或高兴;)
    • @AistisTaraskevicius,很高兴听到这个消息。如果您愿意,请接受答案。
    • 一旦允许我在 7 分钟内完成。
    • 请注意,(++) 的这些递归使用将具有多项式时间。
    猜你喜欢
    • 2012-04-17
    • 2015-06-25
    • 1970-01-01
    • 2013-02-02
    • 2021-12-31
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多