我正在寻找一种在Haskell中动态定义函数的方法,或者Haskell的惯用等价物,而我显然不知道这个等价物。
场景如下:我有一个tagWithAttrs
函数,根据提供的String
参数生成新函数。 定义大致如下:
tagWithAttrs :: String -> ([(String, String)] -> [String] -> String)
tagWithAttrs tagName = [...] -- Implementation ommited to save room.
h1 :: [(String, String)] -> [String] -> String
h1 = tagWithAttrs "h1"
main :: IO ()
main = putStrLn $ h1 [("id", "abc"), ("class", "def")] ["A H1 Test"]
-- Should display '<h1 id="abc" class="def">A H1 Test</h1>'.
到目前为止一切都很好。但是我分配
data HtmlTag = H1 | H2 | H3 deriving (Eq, Show)
,然后构建一个地图(如ertes所建议的),键为HtmlTag
,使用Show实例和现有的tagWithAttrs函数。然后创建一个新函数tag :: HtmlTag -> [(String,String)] -> [String] -> String
,在地图中查找标记,您将使用它作为putStrLn $ tag H1 ...
。这仍然有点冗长。 - John L