[Haskell-beginners] Re: text file to data type
Heinrich Apfelmus
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
>> where
>> 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"
http://www.brics.dk/RS/98/12/BRICS-RS-98-12.pdf
applies. Here's the code:
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
parse = map (convert format . B.split '\t') . B.lines
where
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
magic type.
Regards,
Heinrich Apfelmus
--
http://apfelmus.nfshost.com
More information about the Beginners
mailing list