4

How to convert list of numbers to list of strings(one string = one number from list) in Haskell.

[Int] -> [String]

Examples: [1,2,3,4] -> ["1","2","3","4"]

2
  • Take a look at this which do the inverse (string to int) Commented Nov 21, 2016 at 12:27
  • If you have a function Int -> String you could make a function [Int] -> [String] using map` map :: (a -> b) -> [a] -> [b]` Commented Nov 21, 2016 at 13:32

3 Answers 3

6

If you have a function f :: a -> b, then map f :: [a] -> [b] applies f on all the list elements.

The function show can convert "printable" types in their string representation. In particular, one of the possible types for show is Int -> String.

Use both tools.

Sign up to request clarification or add additional context in comments.

Comments

1

If you need to write a function to print an element from 0, this could be another solution

cp_log :: (Show a) => [a] -> String

cp_log [] = ""
cp_log [x] = (show x)
cp_log (x:xs) = (show x) ++ ", " ++ cp_log xs

A complete example can be the following one

cp_log :: (Show a) => [a] -> String
    
cp_log [] = ""
cp_log [x] = (show x)
cp_log (x:xs) = (show x) ++ ", " ++ cp_log xs

quick_sort :: (Ord a) => [a] -> [a]
quick_sort [] = []
quick_sort (x:xs) =
  let smaller = quick_sort [a | a <- xs, a <= x]
      bigger = quick_sort [a | a <- xs, a > x]
  in smaller ++ [x] ++ bigger

main =
  let sorted = (quick_sort [4, 5, 3, 2, 4, 3, 2])
  in putStrLn (cp_log sorted)

6 Comments

All the TS was needed is simple map show. What you came up with is a rough equivalent of intercalate "," . map show. So your answer doesn't answers the question, and is excessively complicated at the same time. Please pay attention to what was the question about next time :)
ops, I'm sorry :) I try only to post a craft approach, but you have right
There's nothing wrong with that, please accept my apologies. Your haskell is impressive, I think you could help somebody with their pending questions, let's forget about this ancient-one :)
don't worry @madbird, I will happy if you remove the downvote :)
Unfortunately, my downvote is locked until the answer is edited. Add a couple of lines, or, maybe, replace let with where, so I'll be able to remove my vote.
|
0

Using the list monad:

f :: [Int] -> String
f xs = do 
         x <- xs
         return $ show x 

or equivalently:

f' :: [Int] -> [String]
f' = (>>= return.show)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.