在Haskell中读取int

在Haskell中读取int

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

问题描述

我一直在研究Haskell,更具体的是

解决方案

这是一个从字符串 :

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

readMany ::阅读a =>字符串 - > [a]
readMany = unfoldr $ listToMaybe。 concatMap读取。尾巴

例如:

 > readMany我喜欢数字7,11和42. :: [Int] 
[7,11,42]

to jozefg的功能 getNumber :

  justOne :: [a]  - > ;也许是
justOne [x] =只是x
justOne _ = Nothing

getNumber :: String - >也许Int
getNumber = justOne。 readMany

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

  getNumber = listToMaybe。 readMany 


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

and this text:

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

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

解决方案

Here is a function that extracts multiple readable things from a String:

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

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

So for example:

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:29