[Haskell-beginners] Re: text file to data type
apfelmus at quantentunnel.de
Wed Dec 9 05:38:15 EST 2009
Patrick LeBoutillier wrote:
> Heinrich Apfelmus wrote:
>> import Data.ByteString.Lazy.Char8 as B
>> parse = map (zipWith ($) formats . B.split '\t') . B.lines
>> formats = [str, str, int, int, int, int, int,
>> int, int, float, float]
>> int = fst . fromJust . readInt
>> float = \s -> read (unpack s) :: Double
>> str = id
> I've been looking at this example and I can't figure it out how it works.
> Seems to me that "formats" is a list of functions that return different types.
> How does this work?
Oops. It doesn't. :D
Mea culpa, the functions having different types is indeed a problem.
Fortunately, the trick from Oliver Danvy's "Functional Unparsing"
applies. Here's the code:
import qualified Data.ByteString.Lazy.Char8 as B
parse = map (convert format . B.split '\t') . B.lines
format = str . str . int . int . int . int
. int . int . int . float . float
int = lift $ fst . fromJust . B.readInt
float = lift $ \s -> read (B.unpack s) :: Double
str = lift $ id
lift :: (a -> b) -> ([a] -> c) -> ([a] -> (b,c))
lift f k (x:xs) = (f x, k xs)
convert k = k nil where nil  = ()
This time, I've also tested it in GHCi. Try :type parse to see the
More information about the Beginners