[英]Convert a Monadic value to Non-monadic
I am new to Haskell. 我是Haskell的新手。 I need to read the contents from a directory (ie list all the files in the directory) and convert it to HTML. 我需要从目录中读取内容(即列出目录中的所有文件)并将其转换为HTML。 I have a codebase which uses the Yesod framework. 我有一个使用Yesod框架的代码库。
Now, I was able to read the directory contents using getDirectoryContents
which returns type of IO [FilePath]
. 现在,我可以使用getDirectoryContents
读取目录内容,该目录返回IO [FilePath]
类型。 I want to be able to represent this in HTML. 我希望能够用HTML表示。
Can someone help me on this? 有人可以帮我吗? So far this is what I have tried. 到目前为止,这是我尝试过的。 The error that I get is: Couldn't match type 'IO' with 'Text.Blaze.Internal.MarkupM' Expected type: Text.Blaze.Internal.MarkupM Html Actual type: IO Html
我得到的错误是: Couldn't match type 'IO' with 'Text.Blaze.Internal.MarkupM' Expected type: Text.Blaze.Internal.MarkupM Html Actual type: IO Html
Please check the code below: 请检查以下代码:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
import Yesod.Core
import Text.Blaze.Html (toValue, (!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as HA
import System.Directory as FS
getTestHamletR = defaultLayout $ do
setTitle "Test Hamlet"
toWidget $ \render -> do
H.p $ do
result <- fmap toHtml $ getListOfFiles "/home/chetan"
result
Here is the getListOfFiles
function: 这是getListOfFiles
函数:
getListOfFiles::FilePath -> IO [FilePath]
getListOfFiles fpath = FS.getDirectoryContents fpath
I'm not well versed in Yesod, but this should work. 我不太熟悉Yesod,但这应该可以。
You cannot convert an IO
value to non-IO value. 您无法将IO
值转换为非IO值。 However, you can work with these values, while staying in IO
. 但是,您可以在保持IO
同时使用这些值。 To say it somewhat incorrectly, you can work with these values while being inside IO. 说得有些不对劲,您可以在IO内使用这些值。 Ie this should work (not-tested): 即这应该工作(未经测试):
getTestHamletR = do
files <- liftIO $ getListOfFiles "/home/chtan"
defaultLayout $ do
setTitle "Test Hamlet"
toWidget $ \render -> do
H.p $ toHtml (intercalate ", " files)
I guess that getTestHamletR
is not directly IO
, but it is some layer above IO
, so we can use liftIO
to convert the IO [FilePath]
to m [FilePath]
where m
is the Monad yesod uses. 我想, getTestHamletR
不直接IO
,但它是上述一些层IO
,所以我们可以使用liftIO
转换的IO [FilePath]
至m [FilePath]
其中m
是单子耶索德使用。
The getTestHamletR
is an IO
function - every line works inside IO
, you get the directory contents as IO [FilePath]
and you essentially convert it to IO Html
. getTestHamletR
是一个IO
函数-每行都在IO
内部运行,您将目录内容作为IO [FilePath]
,并将其本质上转换为IO Html
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.