我想从一个看起来像这样的文件中读取行:
1 2.1
2 2.2
3 2.3
Run Code Online (Sandbox Code Playgroud)
每行都有一个简单的Int和Float
这就是我想出来的,阅读每一行:
readFoo :: String -> (Int, Float)
readFoo line = (read (splitOn " " line !! 0), read (splitOn " " line !! 1))
Run Code Online (Sandbox Code Playgroud)
或者我也做了一个数据类型,然后read
部分很简单.
data Foo = Foo Int Float deriving (Show, Read)
getM (Foo m p) = m
getP (Foo m p) = p
readFoo :: String -> Foo
readFoo line = read $ "Foo " ++ line :: Foo
Run Code Online (Sandbox Code Playgroud)
但是必须有一种更简单的方法来做到这一点,对吧?
sha*_*ang 10
表达这一点的一种巧妙方法是使用ViewPatterns
扩展名
{-# LANGUAGE ViewPatterns #-}
readFoo :: String -> (Int, Float)
readFoo (words -> [read -> i, read -> f]) = (i ,f)
Run Code Online (Sandbox Code Playgroud)
在标准Haskell中编写它的另一种方法是例如
readFoo :: String -> (Int, Float)
readFoo ln = (read i, read f) where
[i, f] = words ln
Run Code Online (Sandbox Code Playgroud)
当然,所有这些都假设您不关心错误处理.
归档时间: |
|
查看次数: |
112 次 |
最近记录: |