给定一个包含数字的字符串,提取这些数据的最佳方法是什么? [英] Given a string containing numbers, What is the best way to extract these?

查看:147
本文介绍了给定一个包含数字的字符串,提取这些数据的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表如下:

[75,95 64,17 47 82]



如何将其转换为Ints列表;

  [75,95,64,我的直觉是使用map和一个匿名函数?


解决方案

Haskell有几个有用的函数

  read :: String  - > Int  - 限制为清楚起见
map ::(a - > b) - > [a] - > [b]
words :: String - > [String]
concatMap ::(a - > [b]) - > [a] - > [b]

所以你给 map a函数和一个列表,它会将你的函数应用到列表的每个元素。现在知道这一点,你应该可以自己解决它。

正如Gabriel指出的那样,您还需要 concatMap words 确保你的字符串只有1个数字。 words 会将字符串拆分为一串字串, concatMap 会在每个元素上运行并将结果一起粉碎。



如果你不小心,阅读会炸毁你的脸,因为如果字符串格式不正确,它会调用 error 这将终止你的程序。如果这是一个问题,可以使用类似的过程:

  mapMaybe ::(a  - >也许b) - > ; [a]  - > [b] 
readMaybe :: String - >为了清晰起见,可能是Int - Restricted

from Data.Maybe Text.Read


I have a list of strings as follows;

["75","95 64","17 47 82"]

How can I convert this to a list of Ints;

[75,95,64,17,47,82]

My instinct is to use map and an anonymous function?

解决方案

Haskell has a few useful functions

read :: String -> Int -- Restricted for clarity
map  :: (a -> b) -> [a] -> [b]
words :: String -> [String]
concatMap :: (a -> [b]) -> [a] -> [b]

So you give map a function and a list and it will apply your function to each element of the list. Now knowing this, you should be able to solve it yourself.

As Gabriel pointed out you'll also need concatMap and words to make sure that your string only has 1 number in it. words will split the string into a string of words and concatMap will run it over each element and smash the result back together.

Do know that read will blow up in your face if you're not careful since if the string is malformed it will call error which will terminate your program. If this is a concern, a similar process can be followed with

 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
 readMaybe  :: String -> Maybe Int -- Restricted for clarity

from Data.Maybe and Text.Read respectively.

这篇关于给定一个包含数字的字符串,提取这些数据的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆