如何将字符串添加到 Haskell 中的 Monad 列表
How can you add a String to a list of Monads in Haskell
我是函数式编程的新手。我正在使用 Scalpel 抓取一个网站,我需要从该网站包含的 link 中提取信息。我可以推断的只是 link 的一部分,我需要将字符串 "http://www.google.com/"
添加到这些 link 中的每一个。我无法执行正常的 ++
,因为我没有 String
的列表。
代码如下:
{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.Scalpel
main :: IO ()
main = do
res <- scrapeURL "http://www.whateverLink/" scrapeComic
print res
scrapeComic :: Scraper String [[String]]
scrapeComic =
chroots ("ul" @: ["id" @= "research-teachinglist"]) scrapeLink
scrapeLink :: Scraper String [String]
-- This returns me the parts of the links I want
scrapeLink = (attrs "href" "a")
-- I tried this, but it doesn't work
-- scrapeLink = mapM_ ("http://www.google.com/" ++) (attrs "href" "a")
有什么想法吗?
谢谢
你有
attrs "href" "a" :: Scraper String [String]
和
("http://www.google.com/" ++) :: String -> String
并且您想将后者应用于前者结果列表中的所有 String
元素。
首先,将其应用于列表是
的事情
map :: (a -> b) -> [a] -> [b]
所以在你的情况下,你有
map ("http://www.google.com/" ++) :: [String] -> [String]
这让我们更近了一步。
现在下一个问题是,您有一个计算 Scraper String [String]
而不是纯 [String]
值。但是,Scraper str
is an instance of Functor
对于 str
的任何选择,特别是对于 str ~ String
,即 Scraper String
是 Functor
.
给我们的是一种将纯函数应用于 Scraper String
s 的方法:
fmap :: (a -> b) -> Scraper String a -> Scraper b
特别是,我们有
fmap (map ("http://www.google.com/" ++)) :: Scraper String [String]
导致
scrapeLink :: Scraper String [String]
scrapeLink = fmap (map ("http://www.google.com/" ++)) (attrs "href" "a")
我是函数式编程的新手。我正在使用 Scalpel 抓取一个网站,我需要从该网站包含的 link 中提取信息。我可以推断的只是 link 的一部分,我需要将字符串 "http://www.google.com/"
添加到这些 link 中的每一个。我无法执行正常的 ++
,因为我没有 String
的列表。
代码如下:
{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.Scalpel
main :: IO ()
main = do
res <- scrapeURL "http://www.whateverLink/" scrapeComic
print res
scrapeComic :: Scraper String [[String]]
scrapeComic =
chroots ("ul" @: ["id" @= "research-teachinglist"]) scrapeLink
scrapeLink :: Scraper String [String]
-- This returns me the parts of the links I want
scrapeLink = (attrs "href" "a")
-- I tried this, but it doesn't work
-- scrapeLink = mapM_ ("http://www.google.com/" ++) (attrs "href" "a")
有什么想法吗?
谢谢
你有
attrs "href" "a" :: Scraper String [String]
和
("http://www.google.com/" ++) :: String -> String
并且您想将后者应用于前者结果列表中的所有 String
元素。
首先,将其应用于列表是
的事情map :: (a -> b) -> [a] -> [b]
所以在你的情况下,你有
map ("http://www.google.com/" ++) :: [String] -> [String]
这让我们更近了一步。
现在下一个问题是,您有一个计算 Scraper String [String]
而不是纯 [String]
值。但是,Scraper str
is an instance of Functor
对于 str
的任何选择,特别是对于 str ~ String
,即 Scraper String
是 Functor
.
给我们的是一种将纯函数应用于 Scraper String
s 的方法:
fmap :: (a -> b) -> Scraper String a -> Scraper b
特别是,我们有
fmap (map ("http://www.google.com/" ++)) :: Scraper String [String]
导致
scrapeLink :: Scraper String [String]
scrapeLink = fmap (map ("http://www.google.com/" ++)) (attrs "href" "a")