tags:

views:

201

answers:

2

I have a number 9877342931235. Using Haskell, I need to show it as:

987-734293-123-5

i've tried interspersing the list but of course that puts '-' between every digit. How would I do it to yield the actual result?

+6  A: 

Here's a simple general solution for splitting a list into parts of specified lengths and then joining them together with a specified delimiter:

splitercalate :: [Int] -> [a] -> [a] -> [a]
splitercalate (x:[]) _     s = take x s
splitercalate (x:xs) delim s =
  case splitAt x s of
    (a, []) -> a
    (a, bs) -> a ++ delim ++ splitercalate xs delim bs

In your case splitercalate [3, 6, 3, 1] "-" $ show 9877342931235 would give you what you want.

UPDATE: As Antal S-Z notes in a comment below, you can implement this function more concisely by using functions from Data.List and Data.List.Split:

splitercalate chunks sep = intercalate sep . splitPlaces chunks

You would need to install the split package (probably by doing something like cabal install split), and import the intercalate and splitPlaces functions:

import Data.List (intercalate)
import Data.List.Split (splitPlaces)

The two versions should be equivalent. If you don't mind the extra imports and the dependency on the split package, use Antal S-Z's—it's much nicer.

Travis Brown
Your `splitercalate` function is equivalent to `splitercalate chunks sep = intercalate sep . splitPlaces chunks`; `intercalate` is from `Data.List`, and `splitPlaces` is from [`Data.List.Split`](http://hackage.haskell.org/package/split-0.1.2). Judging from the answers I've seen on StackOverflow, the split package is really underused—it's too bad, because the package is really nice.
Antal S-Z
thats awesome, thanks man so much
Abstract
wats this stuff from the data.list package though?
Abstract
A: 
Yitz