我目前正在嘗試學習OCaml。我正在尋找的這個Python代碼相當於:在OCaml中使用列表作爲函數的參數
f(*l[:n])
我想我會嘗試寫模仿此行爲的功能,但它不能正常工作。下面是代碼:
let rec arg_supply f xs n =
if n = 0 then
f
else
match xs with
| x :: remainder -> arg_supply (f x) remainder (n - 1);;
,這裏是錯誤消息我得到:
Error: This expression has type 'a but an expression was expected of type
'b -> 'a
The type variable 'a occurs inside 'b -> 'a
任何幫助表示讚賞,無論是一個辦法讓我的功能工作,或另一種方式來提供第一列表中的n個元素作爲參數。
編輯:n
是調用該函數所需的參數數量,並且因爲它而不變。
編輯:這一個也不工作。取決於n
值
type ('a, 'r) as_value = ASFunction of ('a -> ('a, 'r) as_value) | ASReturnValue of 'r;;
let rec _arg_supply f_or_rval xs n =
if n = 0 then
f_or_rval
else
match f_or_rval with
| ASFunction func -> (
match xs with
| x :: r -> _arg_supply (func x) r (n - 1)
| _ -> failwith "too few arguments for f"
)
| ASReturnValue out -> out;;
你不能那樣做。 'arg_supply'的類型必須取決於'n'的運行時值。 – melpomene
這是一個典型的[XY問題](http://xyproblem.info/)。你能解釋一下你真正想做的嗎? – Drup
@Drup我想調用一個函數,其中我的參數在列表中,而不必寫'name_of_the_function(List.nth li 0)(List.nth li 1)(List.nth li 2)...'。 而且我知道我嘗試過的解決方案即使工作也無濟於事,因爲返回類型必須是ASFunction,而不是。但是我可以「擴展」我的功能以適應這種類型。 – CodenameLambda