Zhi Ying
Zhi Ying

Reputation: 21

Convert string of digits to integer

I am trying to write this function in Haskell called atoi, which takes a string of digits representing an integer to the integer itself.

For example, atoi "123" should give 123.

Here's my implementation so far:

atoi :: String -> Int
atoi str = show str :: Int

I got an error stating

Couldn't match type

Upvotes: 2

Views: 855

Answers (1)

Netwave
Netwave

Reputation: 42786

Use read:

atoi :: String -> Int
atoi s = read s :: Int

Example:

Prelude> atoi s = read s :: Int
Prelude> atoi "12345"
12345

Upvotes: 4

Related Questions