3 Replies - 4808 Views - Last Post: 13 February 2012 - 01:45 PM

#1 whatquestions  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 34
  • Joined: 15-September 11

how to readfile then store in list?(haskell)

Posted 12 February 2012 - 10:01 AM

foodList::IO[(String,String)]
foodList=do
		s <- readFile "foodBase.txt"
		return (read s)

inside the txt file, there is something like
Fruit Apple
Vegetable Tomato
therefore, i hope the content will store in [(Fruit,Apple),(Vegetable,Tomato)]
so how can i do it??
Is This A Good Question/Topic? 0
  • +

Replies To: how to readfile then store in list?(haskell)

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,203
  • Joined: 21-June 11

Re: how to readfile then store in list?(haskell)

Posted 12 February 2012 - 10:20 AM

read would require the contents of the file to have the form [("bla", "bla"), ("bla", "bla")] in order to give you a [(String, String)], so that won't work.

What you can do is to use lines to turn the string into a list of lines and then map words over that list to turn each line into a list of words. This way you'll end up with a list of lists of words. You can then map over the list to turn each sublist into a pair.
Was This Post Helpful? 1
  • +
  • -

#3 whatquestions  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 34
  • Joined: 15-September 11

Re: how to readfile then store in list?(haskell)

Posted 13 February 2012 - 09:52 AM

getFoodList::IO[FoodInfo]
getFoodList=do
		s <- readFile "foodBase.txt"
		return $ map foodList $ map words $ lines s

foodList::[String]->FoodInfo
foodList [foodName,foodType]=Food foodName foodType


i got the txtfile convert into list
but now having problem of display it.

This post has been edited by whatquestions: 13 February 2012 - 09:52 AM

Was This Post Helpful? 1
  • +
  • -

#4 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,203
  • Joined: 21-June 11

Re: how to readfile then store in list?(haskell)

Posted 13 February 2012 - 01:45 PM

If you make FoodInfo an instance of Show (most easily by deriving it), you can just print the list using print (or at the GHCI prompt).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1