3 ms·
I recently learned about the `interact` function in Haskell, which makes it easy to write programs reading from standard input and write to standard output, jus
by prakashk 13y ago
I recently learned about the `interact` function in Haskell, which makes it easy to write programs reading from standard input and write to standard output, just like many of the Unix tools.
For example, if you want to print the id and name of each user from a file in the /etc/passwd format:
-- display all users: ids and names from /etc/passwd
import Data.List.Split (splitOn)
eachLine :: (String -> String) -> (String -> String)
eachLine f = unlines . map f . lines
showUser :: String -> String
showUser line = fields !! 0 ++ "\t" ++ fields !! 4
where fields = splitOn ":" line
main = interact (eachLine showUser)
This can be run, like (assuming the program is saved in list-users.hs):
$ runhaskell list-users.hs < /etc/passwd
I am very new to Haskell, and I am sure there are other, perhaps better ways to do this.
- Tyr42 13y agoIt looks ok to me, though I might pattern match in the `where fields` part instead of using `!!`. Still looks pretty good. If I was feeling fancy, that `unlines . map f . lines` looks like an isomorphism that we could do something awesome with the lens library. Anyone who knows it better care to show me how to do that?