Is there any haskell function to concatenate list with separator?

前端 未结 5 1535
庸人自扰
庸人自扰 2020-12-07 16:06

Is there a function to concatenate elements of a list with a separator? For example:

> foobar \" \" [\"is\",\"there\",\"such\",\"a\",\"function\",\"?\"]
[         


        
5条回答
  •  我在风中等你
    2020-12-07 16:57

    Yes, there is:

    Prelude> import Data.List
    Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
    "is there such a function ?"
    

    intersperse is a bit more general:

    Prelude> import Data.List
    Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
    "is there such a function ?"
    

    Also, for the specific case where you want to join with a space character, there is unwords:

    Prelude> unwords ["is","there","such","a","function","?"]
    "is there such a function ?"
    

    unlines works similarly, only that the strings are imploded using the newline character and that a newline character is also added to the end. (This makes it useful for serializing text files, which must per POSIX standard end with a trailing newline)

提交回复
热议问题