Haskell - number translation

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

987-734293-123-5

I tried shuffling the list, but of course it puts a '-' between each digit. How can I do this to give a real result?

+3
source share
2 answers

Here is a simple general solution for splitting the list into parts of given lengths and then combining them together with the specified separator:

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 9877342931235will provide you with what you want.

UPDATE: As Antal SZ notes in a comment below, you can implement this function more concisely using functions from Data.Listand Data.List.Split:

splitercalate chunks sep = intercalate sep . splitPlaces chunks

split (, - cabal install split) intercalate splitPlaces:

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

. import split, Antal S-Z's-it .

+6

, 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

concat . splitercalate [3,5,3,1] "-" $ show 9877342931235

0

Source: https://habr.com/ru/post/1747794/


All Articles