简体   繁体   English

Haskell Io字符串转换

[英]Haskell Io string conversion

obrob fp =  do
    a <- [(!!) readData fp 0]
    b <- [(!!) readData fp 2]
   return a --(read a :: Int ,read b::[[Int]] )

I read data from file I get 我从文件中读取数据

["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 return this. readData返回此。 It is Io string list 它是Io字符串列表

But now I want to take first and third element from this list and 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]]
)

with out Io type. 没有Io类型。 I don't want to use monad all time. 我不想一直使用monad。

A feeble attempt at reading your mind: 努力读懂你的想法:

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

I'm assuming your do statement was using the monadic version of list... I'm not quite sure. 我假设你的声明是使用monadic版本的列表......我不太确定。 You need to give more details on the types, for example of readData, fp, etc. 您需要提供有关类型的更多详细信息,例如readData,fp等。

The truth is you can't really "get rid" of the IO. 事实是你无法真正“摆脱”IO。 But this is not the problem it seems to be when you're new to Haskell. 但是,当你刚接触Haskell时,这似乎不是问题。 Look at the type of main: 看看主要的类型:

main :: IO ()

Your whole program - or any program really - is a big IO action thats being evaluated. 您的整个程序 - 或任何程序确实 - 是一个被评估的大型IO动作。 What we try to do is a lot of pure computation along the way. 我们尝试做的是沿途的大量纯计算。

How about this (and my apologies if this only confuses the issue more): 怎么样(如果这只是混淆了这个问题,我很抱歉):

-- 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM