[Haskell-beginners] List Sorting and I/O
daniel.is.fischer at web.de
Sun Sep 12 19:24:17 EDT 2010
On Monday 13 September 2010 00:59:40, Lorenzo Isella wrote:
> Dear All,
> Thanks to the help I got from the list, I was able to (almost) finish a
> script that performs some data postprocessing (and the code is really
> amazingly short).
> Now, there are a few things left.
> Consider the lists
> bs = [4,5,3,1,5,2,7,2,8,2,2,3,3,5,6,7] and
> ms = [2,2,2,2,4,4,4,4,6,6,4,4,4,10,12,14]
> Now, I would like to sort bs (and that is easy) and then (since there is
> a 1-1 correspondence between the elements in ms and bs) re-order the
> elements in ms accordingly i.e. bs would become
> and ms [2,4,4,6,4,2,4,4,2,2,4,10,12,4,14].
> How can I achieve that?
import Data.Ord (comparing)
foo bs ms = unzip . sortBy (comparing fst) $ zip bs ms
> Finally, I would like to be able to save the two lists as plain text
> files (no commas, no brackets).
> I tried writeFile+Show, but this saves the lists exactly as printed on
> screen (whereas I simply would like a text file showing a column of
> numbers when opened by your favorite editor).
> Many thanks
One list as a column:
writeFile "bar" $ unlines (map show list)
A list as a space-separated sequence of numbers on one line:
writeFile "bar" $ unwords (map show list)
If you want to output the list elements in a fixed format (fixed width,
right justified; rounded to k decimal places), take a look at Text.Printf.
If you want to output several lists as columns side by side, Text.Printf is
also what you'd be looking for.
More information about the Beginners