我正在努力弄清楚如何创建一个函数,它将函数列表作为输入来生成一些输出。例如, 假设我创建一个名为Func10的类型同义词,如下所示:
type Func10 = Int -> Int
我可以创建一组函数,将值加,减,除或乘以10,如下所示:
add10 :: Func10
add10 input = 10 + input
subtract10 :: Func10
subtract10 input = 10 - input
times10 :: Func10
times10 input = 10 * input
divide10 :: Func10
divide10 input = 10 `div` input
现在让我们说我想创建一个函数,它将获取4个值的列表以及我想要应用于它们的函数列表:add10,subtract10,multiply10和divide10。
最初我以为我可以在需要时给列表中的函数输入整数参数,如下所示:
test_function :: [Func10] -> [Int] -> Int
test_function function input = function[0] (input[1])
main = do
print("print 5 add 10")
print(test_function [add10, subtract10] [3,5,7,9])
这导致以下错误:
function_lists2.hs:17:32: error:
* Couldn't match expected type `[Integer] -> t0 -> Int'
with actual type `[Func10]'
* The function `function' is applied to two arguments,
but its type `[Func10]' has none
In the expression: function [0] (input [1])
In an equation for `test_function':
test_function function input = function [0] (input [1])
|
17 | test_function function input = function[0] (input[1])
| ^^^^^^^^^^^^^^^^^^^^^^
function_lists2.hs:17:45: error:
* Couldn't match expected type `[Integer] -> t0'
with actual type `[Int]'
* The function `input' is applied to one argument,
but its type `[Int]' has none
In the second argument of `function', namely `(input [1])'
In the expression: function [0] (input [1])
|
17 | test_function function input = function[0] (input[1])
| ^^^^^^^^
我认为这可能是因为test_function需要整数输入作为调用test_function的一部分,如下所示:
test_function :: [Func10] -> Int
test_function function = function[0]
main = do
print("print 5 add 10")
print(test_function ([add10, subtract10] 5))
然而,这导致了类似的错误:
function_lists2.hs:26:26: error:
* Couldn't match expected type `[Integer] -> Int'
with actual type `[Func10]'
* The function `function' is applied to one argument,
but its type `[Func10]' has none
In the expression: function [0]
In an equation for `test_function':
test_function function = function [0]
|
26 | test_function function = function[0]
| ^^^^^^^^^^^
function_lists2.hs:30:30: error:
* Couldn't match expected type `Integer -> [Func10]'
with actual type `[Func10]'
* The function `[add10, subtract10]' is applied to one argument,
but its type `[Func10]' has none
In the first argument of `test_function', namely
`([add10, subtract10] 5)'
In the first argument of `print', namely
`(test_function ([add10, subtract10] 5))'
|
30 | print(test_function ([add10, subtract10] 5))
| ^^^^^^^^^^^^^^^^^^^^^
这样做的正确方法是什么?我正在尝试列出一些函数并将它们应用于其他一些值,但很难在线找到有关此主题的信息。感谢。
答案 0 :(得分:1)
像Zpalmtree在评论中所说,错误没有使用!!调用索引。编写代码的正确方法是将其写出来:
test_function :: [Func10] -> [Int] -> Int
test_function function input = (function !! 0) (input !! 1)
main = do
print("print 5 add 10")
print(test_function [add10, subtract10] [3,5,7,9])