Hey guys, I need some help, how can I sum a list from a file using the sum builtin function?
example:
text.txt contains [1,2,3,4]
and i want to get this list from the file and sum these numbers with the sum builtin. Is it possible?
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Sure.
This uses some standard functions from the Prelude:
readFile :: FilePath -> IO Stringreads the file into a string.read :: Read a => String -> aconverts from aStringto any type in theReadtypeclass. You might have to add a type annotation if the compiler couldn’t figure out which type you wanted. In this case the compiler can figure it out since we usedsumon the result, so it infers thatamust be[Integer]. (It actually infersNum a => [a], but this defaults to[Integer]due to type defaulting).readexpects the same format generated byshowon the same type.Note that I had to use do-notation to extract the
StringfromIO Stringin order to applyreadto it.