Haskell - How can I use pure functions inside IO functions?

前端 未结 4 1838
清歌不尽
清歌不尽 2021-01-19 00:14

How can I use pure functions inside IO functions? :-/

For example: I\'m reading a file (IO function) and I want to parse its context, a string, by using a pure funct

4条回答
  •  再見小時候
    2021-01-19 00:23

    Alex Horsman helped me. He said:

    "Perhaps I'm misunderstanding, but that sounds pretty simple? do {x <- ioFunc; return (pureFunc x)}"

    And then I solved my problem:

    import System.IO  
    import Data.List
    
    getFirstPart line Nothing = line
    getFirstPart line (Just index) = fst $ splitAt index line 
    
    eliminateComment line = 
     getFirstPart line $ elemIndex ';' line
    
    eliminateCarriageReturn line =
     getFirstPart line $ elemIndex '\r' line
    
    eliminateEntersAndComments :: String -> String  
    eliminateEntersAndComments text =
     concat $ map mapFunction $ lines text
     where
      mapFunction = (++ " ") . eliminateCarriageReturn . eliminateComment
    
    main = do {
     contents <- readFile "../DWR-operators.txt"; 
     return (eliminateEntersAndComments contents)
    }
    

提交回复
热议问题