別の質問では、コメントの 1 つが次のように述べています[Data.]Text
。String
Text
を に変換する最も簡単な方法は何Data.Text
ですかInt
? read
関数はread
常にString
.
私が思いつくことができる最高のものは次のとおりです。
let fortyTwo = Data.Text.pack "42"
read $ Data.Text.unpack fortyTwo :: Int
より良い方法はありますか?
別の質問では、コメントの 1 つが次のように述べています[Data.]Text
。String
Text
を に変換する最も簡単な方法は何Data.Text
ですかInt
? read
関数はread
常にString
.
私が思いつくことができる最高のものは次のとおりです。
let fortyTwo = Data.Text.pack "42"
read $ Data.Text.unpack fortyTwo :: Int
より良い方法はありますか?
パッケージを見ると、text
というモジュールがありますData.Text.Read
。それはうまくいくようです:
λ> decimal (T.pack "99 bottles")
Right (99," bottles")
λ> decimal (T.pack "a digit")
Left "input does not start with a digit"
つまり、を消費できるパーサーが必要ですText
。Hackage には Text を消費できるパーサーがたくさんあります。 attoparsecを試すことをお勧めします。
import Data.Attoparsec.Text
parseInt = parseOnly (signed decimal)