[英]Defining functor for this stack type in haskell
This is how I have define my Stack type. 这就是我定义堆栈类型的方式。 There could be better ways, but as of now lets stick for this one. 可能会有更好的方法,但是到目前为止,还是坚持这一方法吧。
data Stack' v = Stack' [v] Int deriving (Show)
So something like push' will look like this 所以类似push'的样子
push' :: (Ord v) => Stack' v -> v -> Stack' v
push' (Stack' l m) a = if m <= length l then Stack' l m else Stack' (l ++ [a]) m
But I am not able to define functor for this. 但是我无法为此定义函子。 My this attempt is failing saying that "Parse error in pattern: v" 我的这种尝试失败了,说“解析模式错误:v”
instance Functor Stack' where
fmap f (v l) = (map f v) (l)
Can someone help me in defining the functor? 有人可以帮我定义函子吗?
instance Functor Stack' where
fmap f (Stack' v l) = Stack' (map f v) (l)
Look at type of fmap :: Functor f => (a -> b) -> fa -> fb
and you will find your mistake. 看看fmap :: Functor f => (a -> b) -> fa -> fb
类型fmap :: Functor f => (a -> b) -> fa -> fb
,您会发现错误。
You need to provide a value of type fa
(here f is Stack') and also return a value of type fa
. 您需要提供一个类型为fa
的值(此处f为Stack'),并返回一个类型为fa
的值。
Also you should try avoiding ++
as it is O(n)
where n is the length of first argument. 另外,您应该避免使用++
因为它是O(n)
,其中n是第一个参数的长度。
The simplest definition is: 最简单的定义是:
{-# LANGUAGE DeriveFunctor #-}
data Stack' v = Stack' [v] Int deriving (Show, Functor)
You should avoid length
too because it's O(n)
. 您也应该避免使用length
因为它是O(n)
。
Use a : l
instead of l ++ [a]
- lists can be only efficiently appended at their head, appending to tail is O(n)
. 使用a : l
代替l ++ [a]
-列表只能有效地附加在其头部,附加在尾部为O(n)
。
Your push'
can be rewritten by moving if
inside: 你push'
可以通过移动被重写if
里面:
push' (Stack' l m) a = Stack' (if m <= length l then l else l ++ [a]) m
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.