When is unsafeInterleaveIO unsafe?

前端 未结 4 763
失恋的感觉
失恋的感觉 2021-01-31 05:43

Unlike other unsafe* operations, the documentation for unsafeInterleaveIO is not very clear about its possible pitfalls. So exactly when is it unsafe? I would like

4条回答
  •  攒了一身酷
    2021-01-31 06:01

    Basically everything under "Update" in the question is so confused it's not even wrong, so please try to forget it when you're trying to understand my answer.

    Look at this function:

    badLazyReadlines :: Handle -> IO [String]
    badLazyReadlines h = do
      l <- unsafeInterleaveIO $ hGetLine h
      r <- unsafeInterleaveIO $ badLazyReadlines h
      return (l:r)
    

    In addition to what I'm trying to illustrate: the above function also doesn't handle reaching the end of the file. But ignore that for now.

    main = do
      h <- openFile "example.txt" ReadMode
      lns <- badLazyReadlines h
      putStrLn $ lns ! 4
    

    This will print the first line of "example.txt", because the 5th element in the list is actually the first line that's read from the file.

提交回复
热议问题