简体   繁体   中英

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. It is Io string list

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. I don't want to use monad all time.

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. You need to give more details on the types, for example of readData, fp, etc.

The truth is you can't really "get rid" of the IO. But this is not the problem it seems to be when you're new to Haskell. Look at the type of main:

main :: IO ()

Your whole program - or any program really - is a big IO action thats being evaluated. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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