1

Here's a simplified example of the entries I have in the text files I'm reading --

Set1 1 2 3
Set2 6 7 8

I'm trying to write a function that can convert the above strings into a list of tuples --

[("Set1", [1.0, 2.0, 3.0]), ("Set2", [6.0, 7.0, 8.0])]

This is the function I've written --

parse_input :: String -> [(String, [Float])]
parse_input x = [ (head y, int2float (tail y)) | y <- splitinput ]
    where
        int2float x = [ read a::Float | a <- x ]
        splitinput = [ words a | a <- lines x ]

What bothers me most about this code is the int2float part. It combs through a list of integers and one-by-one converts each one into a float.

Is there a more efficient way to convert a list of integers into a list of floats?

1

1 Answer 1

3

I am not clear about what do you mean by 'efficient way' for this case?

What you are trying to do is to convert [String] to [Float]. I think using read will do just fine. If you really have [Int] then you can use fromIntegral to get any instance of Num type. Just to point you should prefer map instead of list comprehension as it is more readable.

1
  • Thank you for your reply and help, Sativik. I just remembered that Haskell is a lazy language, and that this code only "combs" through the numbers when it needs them. I realized this when I ran this function on an infinite list. Nov 13, 2012 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.