簡體   English   中英

Haskell入門-使用數據構造函數和IO monad組成函數

[英]Beginning Haskell - composing function with data constructor and IO monad

我有以下內容:

import Data.List

data Content
  = TaggedContent (String, [String]) String
  | Null

processContent :: Content -> IO Content
processContent c@(TaggedContent (id, attrs) text) =
  case stripPrefix "include=" a of
       Just f     -> return . TaggedContent (id, attrs) =<< readFile f
       Nothing    -> return c
  where a = head(attrs)
processContent x = return x

transformContent :: Content -> Content
transformContent x = x -- (details of implementation not necessary)

我想用TaggedContent構造函數組成transformContent 也就是說,類似

       Just f     -> return . transformContent TaggedContent (id, attrs) =<< readFile f

但是,這將無法編譯。

我是Haskell的新手,正在嘗試了解正確的語法。

您只需要一個額外的點:

return . transformContent . TaggedContent (id, attrs) =<< readFile f

丹尼爾·瓦格納(Daniel Wagner)解釋了如何進行最小限度的修改以使您的代碼得以編譯。 我將評論一些常見的替代方案。

代碼如

return . g =<< someIOAction

通常也寫成

fmap g someIOAction

要么

g `fmap` someIOAction

或在導入Control.Applicative

g <$> someIOAction

在您的特定情況下,您可以使用:

transformContent . TaggedContent (id, attrs) <$> readFile f

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM