Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String list to an Int list

Tags:

I've got a list of strings, is it possible to convert it to an list of ints?
E.g.:

["1","2"] -> [1,2] 
like image 795
pier Avatar asked May 28 '09 09:05

pier


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .

How do you convert a list of elements into an int?

Method 1: Using eval() Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer.

Can you convert a string to a list?

You can also convert a string to a list using a separator with the split() method. The separator can be any character you specify. The string will separate based on the separator you provide. For example, you can use a comma, , , as the separator.


2 Answers

Well

f :: [String] -> [Int] f = map read 

No?

like image 152
alamar Avatar answered Oct 17 '22 22:10

alamar


This fails:

map read ["1","2"] [*Exception: Prelude.read: no parse 

The way to do it is :

 map (read::String->Int) ["1","2"]  [1,2]  :: [Int] 

Outside of GHCI, in a .hs file it would be:

let intList = map (read::String->Int) ["1","2"] 
like image 39
Luxspes Avatar answered Oct 17 '22 23:10

Luxspes