Bobson
Bobson

Reputation: 233

String list to Int List parsing

I have a String lists which looks like this

String list = ["150";"350";"100"]

I am now trying to parse this into a int list so i can take the values and make calculations with them. The problem i have right now is im quite new to f# and not sure how to do this. I was thinking of making a fold function which run a System.Int32.Parse on every value in a list

let listParser list = List.fold (fun listParser a -> (System.Int32.Parse a) :: intlist) list

This function gives me String list -> Int list, but when i run this function i get

stdin(105,12): error FS0001: This expression was expected to have type
int list    
but here has type
string -> string list 

any better way of doing this? appreciating any form of help!

Upvotes: 1

Views: 118

Answers (2)

John Reynolds
John Reynolds

Reputation: 5057

What you're looking for, is the List.map function:

let list = ["150";"350";"100"] 
let listOfInts = List.map System.Int32.Parse list

Using a lambda, the second line would be

let listOfInts = List.map (fun a -> System.Int32.Parse a) list

but you don't need the lambda in this case.

It's a common practice to use the pipe forward operator when working with collections in F#, like so:

let listOfInts = list |> List.map System.Int32.Parse

Upvotes: 3

Joachim Isaksson
Joachim Isaksson

Reputation: 180897

List.fold doesn't seem like the correct match for your requirement since it's a method that applies a function to each list element and accumulates the result as a single value, such as an average.

You could use List.map though;

> let list = ["150";"350";"100"];;
> let listParser list = List.map System.Int32.Parse list;;
val listParser : list:string list -> int list

> listParser list;;
val it : int list = [150; 350; 100]

Upvotes: 3

Related Questions