簡體   English   中英

在Haskell中讀取int

[英]Reading int's in Haskell

我一直在研究Haskell,更具體地說是IO monad,我想知道如何做到以下幾點:

假設我有這個函數簽名:

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

和本文:

“我的名字是加里,我才21歲”

如果我只想從這句話中讀出數字“21”,我將如何在Haskell中完成?

這可以通過列表處理操作來完成,

import Text.Read
import Data.Char

getNumber :: String -> Maybe Int
getNumber = readMaybe . takeWhile isDigit . dropWhile (not . isDigit)

現在,使用它來構建函數要容易得多。 目前還不清楚Int -> Bool的用途,或者,如果你已經有了字符串,為什么你需要IO 為了獲得你的功能,你可以做類似的事情

yourFunc :: (Int -> Bool) -> IO Int
yourFunc f = do
   r <- fmap getNumber getLine
   case r of
     Nothing -> putStrLn "Please enter a number" >> yourFunc f
     Just x | f x       -> return x
            | otherwise -> putStrLn "Doesn't satisfy predicate" >> yourFunc f

用法:

> yourFunc even
  I am a person
  Please enter a number
  I am 21
  Doesn't satisfy predicate
  I am 22
  22

但是如果你想進行任何嚴肅的解析,我建議使用Parsec或Attoparsec,它們都非常易於使用且更加強大。

這是一個從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

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

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

或者您可以稍微寬松一點,並在指定多個時選擇第一個數字:

getNumber = listToMaybe . readMany

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM