问题描述
Shell-monad supports variable arguments,但是我找不到将此类参数列表传递给追加的方法。也许可以使用该库中存在的函数构造来解决,但我想问一下一般问题。
我已经模糊地理解“varargs”机制是通过函数组合实现的,并且通过使用类型类推断来终止递归。
以该库为例,我想知道是否可以将参数视为“第一类”,例如将两个参数分配给一个变量。
Prelude Control.Monad.Shell Data.Text> f xs = cmd "cat" xs
Prelude Control.Monad.Shell Data.Text> let a = static ("a" :: Text)
Prelude Control.Monad.Shell Data.Text> let a2 = [a,a]
Prelude Control.Monad.Shell Data.Text> f a2
<interactive>:42:1: error:
• Could not deduce (Param [Term Static Text])
arising from a use of ‘f’
from the context: CmdParams t2
bound by the inferred type of it :: CmdParams t2 => t2
at <interactive>:42:1-4
• In the expression: f a2
In an equation for ‘it’: it = f a2
解决方法
没有什么是多态递归解决不了的:
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)
。 (注:cmdList = list . cmd
不 工作!)
接受包含不同类型的列表会比较嘈杂,但可以使用存在类型。
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
来定义。