开发者

Polynomial in Haskell troubles with map

I need to multiply a polynomial by a number using map. I´ve been trying for a long time and I´m already getting crazy. I´ve tried two ways getting this errors:

data Pol = P [(Float,Int)] deriving Show

prodEsc :: Pol -> Float -> Pol
prodEsc (P a) n = P (prodAux a n)

--First try:
prodAux :: [(Float,Int)] -> Float -> [(Float,Int)]
prodAux [] _ = []
prodAux ((c,g):xs) n = map (\ (c,g) n -> (c*n,g)) xs 

--error:
ERROR file:.\Febrero开发者_运维问答 2011.hs:21 - Type error in explicitly typed binding
*** Term           : prodAux
*** Type           : [(Float,Int)] -> Float -> [Float -> (Float,Int)]
*** Does not match : [(Float,Int)] -> Float -> [(Float,Int)]

--Second try:
prodAux :: [(Float,Int)] -> Float -> [(Float,Int)]
prodAux [] _ = []
prodAux (x:xs) n = map (opera x n) (x:xs)

opera :: (Float,Int) -> Float -> (Float,Int)
opera (c,g) n = (c*n,g)

--error:
ERROR file:.\Febrero 2011.hs:23 - Type error in application
*** Expression     : map (opera x n) (x : xs)
*** Term           : opera x n
*** Type           : (Float,Int)
*** Does not match : (Float,Int) -> a

Could anyone help me please?.

Thank you so much!!


When you're using map, you don't need to do your own pattern matching on whether the list is empty or not. So I strongly suspect that instead of

prodAux [] _ = []
prodAux ((c,g):xs) n = map (\ (c,g) n -> (c*n,g)) xs 

you mean simply

prodAux xs n = map (\ (c,g) -> (c*n,g)) xs

Otherwise you would be throwing away the first (c,g) pair, which does not appear to make much sense.


Your first try is right. Just remove the n from the lambda. It is already in scope and not needed:

prodAux :: [(Float,Int)] -> Float -> [(Float,Int)]
prodAux [] _ = []
prodAux ((c,g):xs) n = map (\ (c,g) -> (c*n,g)) xs

map has the type (a -> b) -> [a] -> [b]. this means, that it takes a list of something and applies a function to every element. This function has to have exactly one argument: The element to operate over.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜