How monadicIO works

痞子三分冷 提交于 2020-03-22 09:03:11

问题


I have the following code

fastShuffle :: [a] -> IO [a]
fastShuffle a = <some code>

prop_fastShuffle_correct :: [Int] -> Property
prop_fastShuffle_correct s =  
  monadicIO ( do
    sh <- run (fastShuffle s) 
    return ( True ==> ( insertionSort sh == insertionSort s  && 
                        if length s > 10 
                          then s /= sh 
                          else True ) ) )

And .. it is working. I can't understand how what looks to be a pure function (prop_fastShuffle_correct) can call a non pure function that has side effects (fastShuffle).

Hope that someone can explain.

Thanks!


回答1:


Functions in Haskell never have side effects.

There are only values with side effects, like getLine (which is a value, not a function). getLine is the instruction "read a line of text from standard in". It's not a function that executes the instruction, it is the instruction.

And putStrLn is not a function which writes text to standard out. putStrLn is a function, which takes a string as a parameter, and returns an instruction to write that string to standard out.

There is no problem with storing these instructions in pure data structures. If you want to actually execute them, however, then at some point they must be part of the main program value main.



来源:https://stackoverflow.com/questions/60538598/how-monadicio-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!