没有什么是一点多态递归不能解决的:
cmdList :: (Param command, Param arg, CmdParams result) =>
command -> [arg] -> result
cmdList command = go . reverse where
go :: (Param arg, CmdParams result) => [arg] -> result
go [] = cmd command
go (arg:args) = go args arg
在 ghci 中尝试一下:
> Data.Text.Lazy.IO.putStr . script $ cmdList "cat" ["dog", "fish"]
#!/bin/sh
cat dog fish
它需要给出的所有参数cmdList
具有相同的类型,尽管它仍然接受之后不以列表形式存在的其他类型的附加参数。
如果您愿意打开扩展程序,您甚至可以让它接受多个位置的列表,每个位置可能有不同的类型。
list :: (Param arg, CmdParams result) =>
(forall result'. CmdParams result => result') ->
[arg] -> result
list f [] = f
list f (arg:args) = list (f arg) args
使用它的一个例子:
> T.putStr . script $ list (list (cmd "cat") ["dog", "fish"] "bug") ["turtle", "spider"]
#!/bin/sh
cat dog fish bug turtle spider
以前的cmdList
可以定义为cmdList command = list (cmd command)
. (N.B. cmdList = list . cmd
does not work!)
接受包含不同类型的列表会产生更多噪音,但对于存在类型来说是可能的。
data Exists c where Exists :: c a => a -> Exists c
elist :: CmdParams result =>
(forall result. CmdParams result => result) ->
[Exists Param] -> result
elist f [] = f
elist f (Exists arg:args) = elist (f arg) args
但看看使用起来有多么烦人:
> T.putStr . script $ elist (cmd "cat") [Exists "dog", Exists "fish"]
#!/bin/sh
cat dog fish
以前的list
可以通过它来定义list f = elist f . map Exists
.