Home > OS >  De-sugaring Do-Notation Function
De-sugaring Do-Notation Function

Time:10-12

sugar a function that use's Do notation. But I'm struggling somewhat with creating/converting the function to using >>= and lambda's only. Any help appreciated.

This function takes a filepath, reads it, turns it into a list, then it takes the resulting list, splits it in half, based on its length, and lastly writes two files one taking the first half of the list, and one file consisting of the second half of the list. That is the idea anyway.

splitFile :: FilePath -> IO ()
splitFile file = do
  x <- readFileUTF8 file
  let y = splitAt (div (length $ lines x) 2) $ lines x
  writeFile "/tmp/foo.txt-part1" $ unlines $ fst y
  writeFile "/tmp/foo.txt-part2" $ unlines $ snd y

CodePudding user response:

splitFile :: FilePath -> IO ()
splitFile file =
  readFileUTF8 file >>= \x ->
    let y = splitAt (div (length $ lines x) 2) $ lines x in 
      (writeFile "/tmp/foo.txt-part1" $ unlines $ fst y) >>
        (writeFile "/tmp/foo.txt-part2" $ unlines $ snd y)

but you can replace >> .. with >>= \_ -> ...

You can also turn y into a pattern match, but to be completely faithful to the original you need to use a lazy pattern ~(a, b)

    ..
    let (a, b) = splitAt (div (length $ lines x) 2) $ lines x in 
      writeFile "/tmp/foo.txt-part1" (unlines a) >>
        writeFile "/tmp/foo.txt-part2" (unlines b)
  • Related