Comparing patterns with a tuple in IO Monad in Haskell

I study Haskell in my free time and recently moved into the field of monadic functions. I overtook the code from the exercise that I was working on this very contrived example to isolate the exact problem I am having:

import System.Random

rndPermu :: [a] -> IO (a, [a])
rndPermu xs = (front, back)
    where (front, back) = hurf xs

hurf :: [a] -> IO (a, [a])
hurf xs = randomRIO (0, (length xs) - 1) >>= \r -> return $ removeAt r xs

removeAt :: Int -> [a] -> (a, [a])
removeAt n xs = (e, rest)
    where e    = xs !! n
          rest = take n xs ++ (tail $ drop n xs)

rndPermu generates a type error when loading into GHCi, stating that type (t, t1) was expected in the 'where' clause, but IO (a, [a]) was received. I can use things like (liftM fst) to pull individual elements out of a tuple and just assign one value, but this is obviously a careless and devious way to get around things. I feel that I’m probably stumbling upon some slight nuance of syntax that looks in my face. How to resolve this type error? A direct match with a tuple wrapped in a monad should be possible, right?

+3
source share
4 answers

I do not know why you do not have

rndPermu xs = hurf xs

but to answer the question you asked, try this

rndPermu xs = do (front, back) <- hurf xs
                 return (front, back)

, - IO. , <-.

+2

, , rndPermu IO, hurf, IO, rndPermu :: IO a -> a. . IO monad , hurf IO, , hurf, IO: IO . .

, do-notation:

rndPermu :: [a] -> IO (a, [a])
rndPermu xs =
   do (front, back) <- hurf xs
      return (front, back)

, . IO , :

-- pure function to do something with the result of |hurf|
modify :: (a, [a]) -> (a, [a])
modify (a, as) = (a, reverse as)

rndPermu :: [a] -> IO (a, [a])
rndPermu xs =
   do r <- hurf xs
      return (modify r)
-- or, with >>= operator:
-- hurf xs >>= return . modify
+2

do , :

rndPermu xs = hurf xs >>= \(front, back) -> return (front, back)

rndPermu xs = hurf xs >>= \res -> case res of (front, back) -> return (front, back)
+1

, GHCi , rndPermu -. . :

 where (front, back) = hurf xs

(), , . , Haskell ; , . , do, , , -.

0
source

Source: https://habr.com/ru/post/1726725/


All Articles