在Haskell中阅读int&#39 [英] Reading int's in Haskell

查看:50
本文介绍了在Haskell中阅读int&#39的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究Haskell,更具体地说是 IO monad,我想知道我该怎么做:

I've been studying Haskell, more specifically the IO monad, and I would like to know how can i do the following:

假设我具有此功能签名:

Let's say I have this function signature:

getNumber :: String −> (Int −> Bool) −> IO Int  

和此文本:

我叫加里,今年21岁"

"My name is Gary, and I'm 21 years old"

如果我只想从这句话中读取数字"21",我该如何在Haskell中做到这一点?

If I want to read only the number "21" from this sentence, how would I do it in Haskell ?

推荐答案

此处是从 String :

import Data.List (unfoldr, tails)
import Data.Maybe (listToMaybe)

readMany :: Read a => String -> [a]
readMany = unfoldr $ listToMaybe . concatMap reads . tails

例如:

> readMany "I like the numbers 7, 11, and 42." :: [Int]
[7,11,42]

您可以轻松地将其专门化为jozefg的函数 getNumber :

You can easily specialize this to jozefg's function getNumber:

justOne :: [a] -> Maybe a
justOne [x] = Just x
justOne _   = Nothing

getNumber :: String -> Maybe Int
getNumber = justOne . readMany

或者您可以宽大一些,并在指定多个时选择第一个数字:

Or you can be a little more lenient and pick the first number when more than one is specified:

getNumber = listToMaybe . readMany

这篇关于在Haskell中阅读int&#39的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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