Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store in a variable the result of a shell as Int

Tags:

unix

haskell

ghc

So I work with files, and I need to know the largest line in file X. Using Unix awk results in a Int that I'm looking for. But in Haskell how can I return that value and save it to a variable?
I tried define something with IO [Int] -> [Int]

maxline = do{system "awk ' { if ( length > x ) { x = length } }END{ print x }' filename";}

doesn't work cause:

Couldn't match expected type 'Int',against inferred type 'IO GHC.IO.Exception.ExitCode'
like image 426
MrFabio Avatar asked Jan 14 '12 05:01

MrFabio


2 Answers

This is because the system action returns the exit status of the command you run which cannot be converted to Int. You should use the readProcess to get the commands output.

> readProcess "date" [] []
  "Thu Feb  7 10:03:39 PST 2008\n"

Note that readProcess does not pass the command to the system shell: it runs it directly. The second parameter is where the command's arguments should go. So your example should be

readProcess "awk" [" { if ( length > x ) { x = length } }END{ print x }", "/home/basic/Desktop/li11112mp/textv"] ""
like image 56
Abhinav Sarkar Avatar answered Nov 15 '22 09:11

Abhinav Sarkar


You can use readProcess to get another program's output. You will not be able to convert the resulting IO String into a pure String; however, you can lift functions that expect Strings into functions that expect IO Strings. My two favorite references for mucking about with IO (and various other monads) are sigfpe's excellent blog posts, You Could Have Invented Monads! (And Maybe You Already Have.) and The IO Monad for People who Simply Don't Care.

For this particular problem, I would strongly suggest looking into finding a pure-Haskell solution (that is, not calling out to awk). You might like readFile, lines, and maximumBy.

like image 26
Daniel Wagner Avatar answered Nov 15 '22 11:11

Daniel Wagner