Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two files in haskell / passing two IO Strings to one function

Tags:

haskell

monads

I'm new to Haskell and monads and I'm trying to write a simple program that loads two files into Strings and then compares the String as Char-lists using a comparison-function (which later on should be replaced by something fancy). But I couldn't figure out how to pass these IO lists to the comparison function and to the final print output... In the code

import System.IO  
import Control.Monad


cmp :: (Eq a) => [a] -> [a] -> Bool
cmp []      []      = True
cmp []      (y:ys)  = False
cmp (x:xs)  []      = False
cmp (x:xs)  (y:ys)  = (x==y) && cmp xs ys

main = do
    l1 <- readFile "dat1"
    l2 <- readFile "dat2"
    print . cmp =<< l1 =<<l2

the last line

print . cmp =<< l1 =<<l2

does not work and has to be replaced... But how to do that?

Thanks a lot for any suggestions in advance

like image 463
user3502977 Avatar asked Feb 14 '23 07:02

user3502977


2 Answers

l1 and l2 are already String, so you can use print $ cmp l1 l2 directly.

like image 171
Lee Duhem Avatar answered Feb 16 '23 01:02

Lee Duhem


There is also an alternate way to do that: liftM2 cmp will have type IO [a] -> IO [a] -> IO Bool, so liftM2 cmp (readFile "dat1") (readFile "dat2") is IO Bool and you can write

main = print =<< liftM2 cmp (readFile "dat1") (readFile "dat2")
like image 36
Alexey Romanov Avatar answered Feb 16 '23 00:02

Alexey Romanov