Reputation: 15
I'd greatly appreciate if you could tell me how to make a single string from a range between two ints. Like [5..10] i would need to get a "5678910". And then I'd have to calculate how many (zeroes, ones ... nines) there are in a string.
For example: if i have a range from [1..10] i'd need to print out
1 2 1 1 1 1 1 1 1 1
For now i only have a function to search for a element in string.
`countOfElem elem list = length $ filter (\x -> x == elem) list`
But the part how to construct such a string is bugging me out, or maybe there is an easier way? Thank you.
I tried something like this, but it wouldn't work.
let intList = map (read::Int->String) [15..22]
Upvotes: 1
Views: 371
Reputation: 120741
I tried something like this, but it wouldn't work.
let intList = map (read::Int->String) [15..22]
Well... the purpose of read
is to parse strings to read-able values. Hence it has a type signature String -> a
, which obviously doesn't unify with Int -> String
. What you want here is the inverse1 of read
, it's called show
.
Indeed map show [15..22]
gives almost the result you asked for – the numbers as decimal-encoded strings – but still each number as a seperate list element, i.e. type [String]
while you want only String
. Well, how about asking Hoogle? It gives the function you need as the fifth hit: concat
.
If you want to get fancy you can then combine the map
and concat
stages: both the concatMap
function and the >>=
operator do that. The most compact way to achieve the result: [15..22]>>=show
.
1show
is only the right inverse of read
, to be precise.
Upvotes: 3