好吧,看来我对哈斯克尔的态度很糟糕,我发誓我一直困扰着所有这些问题。无论如何,我需要拿两个列表,压缩它们,然后用总和来映射。所以这就是我到目前为止所做的事情并没有奏效:
zipMapList :: [a] -> [a] -> [a]
zipMapList x y = do
let zipList = zip x y
let mapList = map + zipList
mapList
好的,这是我在尝试加载文件时遇到的错误:
HW2.hs:18:25: error:
• Couldn't match expected type ‘(a1 -> b) -> [a1] -> [b]’
with actual type ‘[(a, a)]’
• In the second argument of ‘(+)’, namely ‘zipList’
In the expression: map + zipList
In an equation for ‘mapList’: mapList = map + zipList
• Relevant bindings include
mapList :: (a1 -> b) -> [a1] -> [b] (bound at HW2.hs:18:9)
zipList :: [(a, a)] (bound at HW2.hs:17:9)
y :: [a] (bound at HW2.hs:16:14)
x :: [a] (bound at HW2.hs:16:12)
zipMapList :: [a] -> [a] -> [a] (bound at HW2.hs:16:1)
18 | let mapList = map + zipList |
HW2.hs:19:5: error:
• Couldn't match expected type ‘[a]’
with actual type ‘(a0 -> b0) -> [a0] -> [b0]’
• Probable cause: ‘mapList’ is applied to too few arguments
In a stmt of a 'do' block: mapList
In the expression:
do let zipList = zip x y
let mapList = map + zipList
mapList
In an equation for ‘zipMapList’:
zipMapList x y
= do let zipList = ...
let mapList = ...
mapList
• Relevant bindings include
zipList :: [(a, a)] (bound at HW2.hs:17:9)
y :: [a] (bound at HW2.hs:16:14)
x :: [a] (bound at HW2.hs:16:12)
zipMapList :: [a] -> [a] -> [a] (bound at HW2.hs:16:1)
19 | mapList | ^^^^^^^
我只是没有得到错误的含义,我的意思是我得到一个列表[a]和另一个列表[a]然后我将它们压缩并映射然后得到另一个列表,它没有&#t; t让我理解为什么我会得到元组错误,有人能伸出援助之手吗?
答案 0 :(得分:2)
map + zipList
尝试将map
与zipList
相加,如x+y
中所示。在那里,您希望将+
作为函数传递,因此它应该是map (+) zipList
。
但是等等。 zipList
是对的列表,(+)
不会将一对作为输入:
-- simplified types for clarity
(+) :: Int -> Int -> Int
-- but we want
add :: (Int, Int) -> Int
可能的解决方案是定义我们自己的add
add (x,y) = x+y
-- ...
map add zipList
或使用lambda
map (\ (x,y) -> x+y) zipList
或取消+
:
map (uncurry (+)) zipList
另请注意,您的类型有误,您需要a
作为数字类型才能求和。
zipMapList :: Num a => [a] -> [a] -> [a]
zipMapList xs ys = map (uncurry (+)) (zip xs yz)
-- or, exploiting zipWith
zipMapList xs ys = zipWith (+) xs yz
答案 1 :(得分:0)
map
是map :: (a -> b) -> [a] -> [b]
类型的函数,zip
类型为zip :: [a] -> [b] -> [(a, b)]
。当您编写map + zipList
时,您尝试将(a -> b) -> [a] -> [b]
类型的元素添加到[(a,b)]
类型的元素中 - 您能看到它是如何运作的吗?
至于你如何实现你想要的,这将是算法:
(+)
函数的类型是什么 - 它不适用于元组,而是两个不同的输入。因此,在进行添加之前,需要将元组分成2个输入map
应用于压缩列表。