Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

数字の文字列をread使って数字列に変換する

More than 5 years have passed since last update.

やり方

read . returnを使って型を指定すれば良い

Prelude> let n = "123456789" :: String
Prelude> n
"123456789"
Prelude> map return n :: [String]
["1","2","3","4","5","6","7","8","9"]
Prelude> map (read . return) n :: [Int]
[1,2,3,4,5,6,7,8,9]
Prelude> map (read . return) n :: [Float]
[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]

[String]の場合には以下のようにmapしてあげれば良い

Prelude> let parse str = map (read . return) str :: [Int]
Prelude> :t parse
parse :: [Char] -> [Int]
Prelude> map parse ["1234","5678","9012"]
[[1,2,3,4],[5,6,7,8],[9,0,1,2]]
Prelude> map product $ map parse ["1234","5678","9012"]
[24,1680,0]

ちょっと詳しく

大事なのはこの型指定

Prelude> map (read . return) n :: [Int]

returnをリスト(モナド)への変換操作として用いており、
さらにreadの返り値としてIntを同時に指定している

分解するとこうなる

Prelude> let x = return "100" :: [String]
Prelude> x
["100"]
Prelude> map read x :: [Int]
[100]

当然リスト以外を使うことも出来て、
例えば文字列をMaybe Intに変換したければfmapを使って以下のように書ける

Prelude> fmap read $ return "100" :: Maybe Int
Just 100
Prelude> let x = return "100" :: Maybe String
Prelude> fmap read x :: Maybe Int
Just 100

使えるシーン

Problem 8 - Project Euler

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away