Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputting Data with Haskell

Back Story: In an attempt to better understand Haskell and functional programming, I've given myself a few assignments. My first assignment is to make a program that can look through a data set (a set of numbers, words in a blog, etc), search for patterns or repetitions, group them, and report them.

Sounds easy enough. :)

Question: I'd like for the program to start by creating a list variable from the data in a text file. I'm familiar with the readFile function, but I was wondering if there was a more elegant way to input data.

For example, I'd like to allow the user to type something like this in the command line to load the program and the data set.

./haskellprogram textfile.txt

Is there a function that will allow this?

like image 365
subtlearray Avatar asked Jan 05 '12 18:01

subtlearray


2 Answers

import System.Environment

main :: IO ()
main = do
  args <- getArgs
  -- args is a list of arguments
  if null args
    then putStrLn "usage: ./haskellprogram textfile.txt"
    else do contents <- readFile $ head args
            putStrLn $ doSomething contents

doSomething :: String -> String
doSomething = reverse

That should be enough to get you started. Now replace reverse with something more valuable :)

Speaking of parsing some input data, you might consider breaking your data into lines or words using respective functions from Prelude.

like image 155
Jan Avatar answered Sep 24 '22 16:09

Jan


You're looking for getArgs function.

like image 36
duri Avatar answered Sep 25 '22 16:09

duri