使用散布和展示

san*_*nic 0 haskell

我正在尝试获取此代码:

intersperse ',' $ show 123
Run Code Online (Sandbox Code Playgroud)

集成到此功能:

printListTuples listTuple = unlines [ ys ++ " " ++ unwords (map show x) | (x, ys) <- listTuple ]
Run Code Online (Sandbox Code Playgroud)

其中x对于此示例可以等于123.

因此代码应输出一个字符串,如下所示:"1,2,3"

而不是像这个代码目前那样只是"1 2 3".

我不断尝试在函数中"映射""穿插"和"显示"到x.有什么建议?

编辑:

例如,我尝试过使用

printListTuples listTuple = unlines [ ys ++ " " ++  unwords (map intersperse ',' $ show x) | (x, ys) <- listTuple ]
Run Code Online (Sandbox Code Playgroud)

但是这会返回一个错误:

    Couldn't match expected type ‘String -> [String]’
                with actual type ‘[[a0] -> [a0]]’
    The first argument of ($) takes one argument,
    but its type ‘[[a0] -> [a0]]’ has none
    In the first argument of ‘unwords’, namely
      ‘(map intersperse ',' $ show x)’
    In the second argument of ‘(++)’, namely
      ‘unwords (map intersperse ',' $ show x)’

    Couldn't match expected type ‘[a0]’ with actual type ‘Char’
    In the second argument of ‘map’, namely ‘','’
    In the expression: map intersperse ','
    In the first argument of ‘unwords’, namely
      ‘(map intersperse ',' $ show x)’
Run Code Online (Sandbox Code Playgroud)

我不知道要解决的问题.

Eri*_*ikR 5

尽量避免编写复杂的表达式.您可以使用letwhere子句创建中间定义.然后从较小的测试表达式构建最终表达式.

例如,您已经确定了一个有用的表达式:

intersperse ',' $ show x
Run Code Online (Sandbox Code Playgroud)

所以创建一个封装了这个的定义:

commify x = intersperse ',' (show x)
Run Code Online (Sandbox Code Playgroud)

然后你可以问ghci它的签名:

ghci> :t commify
commify :: Show a => a -> String
Run Code Online (Sandbox Code Playgroud)

接下来,解决只打印一个元组的问题:

printTuple (x,ys) = ys ++ " " ++ ...
Run Code Online (Sandbox Code Playgroud)

一旦你有了这个工作,你的printListTuple功能就是:

printListTuple listTuples
   = unlines [ printTuple (x,ys) | (x,ys) <- listTuples ]
Run Code Online (Sandbox Code Playgroud)

这很容易阅读和理解.