我刚接触Haskell,有些概念不是很理解。
当我在使用IO时,我想要将 IO [[String]] 压成一维数组。
这是我尝试的代码示例:
module DatabaseTestSO where
import Database.HDBC
import Database.HDBC.MySQL
import Data.Foldable
convSqlValue :: [SqlValue] -> [String]
convSqlValue xs = [ getString x | x <- xs ]
where getString value = case fromSql value of
Just x -> x
Nothing -> "Null"
listValues :: [[SqlValue]] -> [[String]]
listValues [] = []
listValues xs = [ convSqlValue x | x <- xs ]
flatten :: [[a]] -> [a]
flatten = Data.Foldable.foldl (++) []
domains :: IO [[String]]
domains =
do conn <- connectMySQL defaultMySQLConnectInfo {
mysqlHost = "hostname",
mysqlDatabase = "dbname",
mysqlUser = "username",
mysqlPassword = "pass" }
queryDomains <- quickQuery conn "SELECT name FROM domains" []
return (listValues queryDomains)
在GHCi中,使用[[String]]
可以按预期工作:
*DatabaseTestSO> flatten [["blah","blab","wah"],["bloh","blob","woh"],["blih","blib","wuh"]]
["blah","blab","wah","bloh","blob","woh","blih","blib","wuh"]
但不适用于 IO [[String]]
,我该怎么办?
*DatabaseTestSO> flatten domains
<interactive>:1:9:
Couldn't match expected type `[[a0]]'
with actual type `IO [[String]]'
In the first argument of `flatten', namely `domains'
In the expression: flatten domains
In an equation for `it': it = flatten domains
我猜我不能使用一个本应该是纯函数的IO类型?我能把IO [[String]]
转换成 [[String]]
吗?如何正确地解决这个问题?
flatten
被称为concat
,并且定义在Prelude
中。 - Thomas EdingPrelude
会自动导入吗? - matthias krull