简体   繁体   English

如何在 Haskell 中将数字列表转换为字符串列表

[英]How to convert list of numbers to list of strings in Haskell

How to convert list of numbers to list of strings(one string = one number from list) in Haskell.如何在 Haskell 中将数字列表转换为字符串列表(一个字符串 = 列表中的一个数字)。

[Int] -> [String] [整数] -> [字符串]

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

If you have a function f :: a -> b , then map f :: [a] -> [b] applies f on all the list elements.如果您有函数f :: a -> b ,则map f :: [a] -> [b]f应用于所有列表元素。

The function show can convert "printable" types in their string representation.函数show可以在其字符串表示中转换“可打印”类型。 In particular, one of the possible types for show is Int -> String .特别是, show的可能类型之一是Int -> String

Use both tools.使用这两种工具。

If you need to write a function to print an element from 0, this could be another solution如果您需要编写一个函数来打印从 0 开始的元素,这可能是另一种解决方案

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)

Using the list monad:使用列表单子:

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

or equivalently:或等效地:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM