Abstract
Abstract

Reputation: 455

Haskell - interpreting a number

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?

Upvotes: 3

Views: 331

Answers (2)

Travis Brown
Travis Brown

Reputation: 139028

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.

Upvotes: 6

Yitz
Yitz

Reputation: 5117

OK, if you don't want to use Data.List.Split...

import Data.List (intercalate)

splitPlaces (n:ns) x = let (h, t) = splitAt n x in h : splitPlaces ns t splitPlaces _ x = []

splitercalate chunks sep = intercalate sep . splitPlace chunks

Your answer is then concat . splitercalate [3,5,3,1] "-" $ show 9877342931235

Upvotes: 0

Related Questions