【问题标题】:Haskell Io string conversionHaskell Io 字符串转换
【发布时间】:2011-09-17 19:57:45
【问题描述】:
obrob fp =  do
    a <- [(!!) readData fp 0]
    b <- [(!!) readData fp 2]
   return a --(read a :: Int ,read b::[[Int]] )

我从我得到的文件中读取数据

["6",
 "",
 "[[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24],[25,26,27,28,29,30],[31,32,33,34,35,36]]"
]

readData 返回这个。是io字符串列表

但是现在我想从这个列表中取出第一个和第三个元素并返回

(6,
 [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24],[25,26,27,28,29,30],[31,32,33,34,35,36]]
)

没有 Io 类型。我不想一直使用 monad。

【问题讨论】:

标签: string haskell types io


【解决方案1】:

事实上,你无法真正“摆脱” IO。但这不是您刚接触 Haskell 时的问题。看看main的类型:

main :: IO ()

您的整个程序(或任何程序)是一个正在评估的大型 IO 操作。我们尝试做的是在此过程中进行大量纯计算。

这个怎么样(如果这只会使问题更加混乱,我深表歉意):

-- Simulate your file read operation
readData :: IO [String]
readData = return ["6","","[[1,2,3,4,5,6],[7,8,9,10,11,12],
    [13,14,15,16,17,18],[19,20,21,22,23,24],[25,26,27,28,29,30],
    [31,32,33,34,35,36]]"]


-- pure function - not IO
someOtherFunction (x, ys) = (x > 0, length ys)


obrob :: IO (Bool, Int)
obrob = do
   -- Pattern match out the 1st and 3rd elements
   (a:_:b:_) <- readData

   -- t is the tuple you're trying to get to
   let t = ((read a) :: Int, (read b) :: [[Int]])
   print t 

   -- And inside this do block, that t is not in IO.
   -- Lets pass it to a pure function:
   let u = someOtherFunction t

   -- Later we have to evaluate to something in IO.
   -- It cannot be escaped.
   return u

【讨论】:

    【解决方案2】:

    读心术的微弱尝试:

    obrob fp :: Integral i, Read i => (i, [[i]])
    obrob fp = let xs = readData fp
               in (read $ readData fp !! 0, read $ readData fp !! 2)
    

    我假设您的 do 语句使用的是单子版本的 list...我不太确定。您需要提供有关类型的更多详细信息,例如 readData、fp 等。

    【讨论】:

    • 我写了我纠正问题的评论。在 monada IO 中,我需要在返回之前运行 obrob,它会起作用
    • @XYZ 该声明毫无意义。在返回之前运行一些东西?你从什么时候开始在 Haskell 中“运行”?
    猜你喜欢
    • 2013-03-16
    • 2011-10-01
    • 1970-01-01
    • 2023-01-28
    • 2021-10-18
    • 2013-05-01
    • 1970-01-01
    • 2011-08-22
    • 2017-07-22
    相关资源
    最近更新 更多