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?
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?
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 import
s and the dependency on the split
package, use Antal S-Z's—it's much nicer.