LoginSignup
7
7

More than 5 years have passed since last update.

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

Posted at

やり方

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

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7