如何在haskell中编写一个函数,它在String的每个字符后插入空格

Joh*_*hio -3 haskell

我想在haskeel中实现一个方法,它应该在传递给该方法的每个字符串之后添加空格,但不能在字符串的最后一个字符串之后添加空格

Main> insertSpace "This is world"
"T h i s  i s  w o r l d"
Run Code Online (Sandbox Code Playgroud)

Ada*_*ith 5

您可以通过显式递归手动编写此代码.

insertSpace :: String -> String
insertSpace []     = []
insertSpace (x:[]) = x  -- you need this to keep from adding a space at the end
insertSpace (x:xs) = x:' ':(insertSpace xs)
Run Code Online (Sandbox Code Playgroud)

但是这里有一个stdlib函数Data.List- intersperse.

import Data.List (intersperse)

insertSpace :: String -> String
insertSpace = intersperse ' '
Run Code Online (Sandbox Code Playgroud)

这是第一个结果,当您搜索HoogleChar -> String -> String.