【问题标题】:Yesod handlers, content of POSTed filesYesod 处理程序,POSTed 文件的内容
【发布时间】:2013-02-14 00:44:11
【问题描述】:

以下代码:

postImportR = do
    fi <- lookupFiles "file"
    fc <- lift $ fileSource (fi !! 0) $$ consume

似乎可以工作(至少我可以“liftIO $ print fc”),将其拆分为用于迭代的函数不起作用:

process :: [FileInfo] -> [String]
process [] = []
process (f:r) = do
    fn <- fileName f
    fc <- lift $ fileSource f $$ consume
    ([fn] : (process r))

postImportR = do
    fi <- lookupFiles "file"
    process fi

甚至使用 lambda 函数:

files <- L.map (\f -> (fileName f, lift $ fileSource f $$ consume)) fi

在处理程序中它给了我一个我不明白的类型错误。

我的错在哪里——喜欢从文件的行中生成用于数据库导入的内容(当然,还要学习更多 Haskell)。

【问题讨论】:

    标签: haskell yesod


    【解决方案1】:

    你有

    fileName :: FileInfo -> Text
    

    所以你不能直接在 do-block 中使用fileName

    fn <- fileName f
    

    这需要一个 let-binding

    let fn = fileName f
    

    接下来是什么让process :: [FileInfo] -&gt; [String] 不可能(1),

    fileSource :: FileInfo -> Source (ResourceT IO) ByteString
    

    所以

    fc <- lift $ fileSource f $$ consume
    

    你在一个 MonadMonadIO 的 do-block 中,你无法离开可以包装任意 IO-actions 的 Monad,就像你无法离开一样IO 本身。

    你可以拥有的是

    process :: (SomeFiendishConstraint m) => [FileInfo] -> m [Text]
    process [] = return []
    process (f:r) = do
        let fn = fileName f
        lift $ fileSource f $$ consume
        fs <- process r
        return (fn : fs)
    

    或者,更简洁,

    process = mapM (\f -> lift $ fileSource f $$ consume >> return fileName f)
    

    然后

    postImportR = do
        fi <- lookupFiles "file"
        process fi
    

    (1) 禁止unsafePerformIO

    【讨论】:

    • 非常感谢!这很好——但是一步一步来:(1)我知道“地图我还是不太清楚。似乎还有很长的路要走...
    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2017-02-27
    相关资源
    最近更新 更多