Haskell 定义Num的实例
我有一个带有类型声明的模块和一些用于此类型的函数Haskell 定义Num的实例,haskell,Haskell,我有一个带有类型声明的模块和一些用于此类型的函数 module Stream where import Prelude ((+), (-), (<), (++), (*), otherwise, id) import qualified Prelude as P infixr 1 :& data Stream a = a :& Stream a instance P.Show a => P.Show (Stream a) where show xs =
module Stream where
import Prelude ((+), (-), (<), (++), (*), otherwise, id)
import qualified Prelude as P
infixr 1 :&
data Stream a = a :& Stream a
instance P.Show a => P.Show (Stream a) where
show xs = showInfinity (P.show (take 5 xs)) where
showInfinity xs = P.init xs ++ "..."
head :: Stream a -> a
head (x:&_) = x
tail :: Stream a -> Stream a
tail (_:&xs) = xs
(!!) :: Stream a -> P.Int -> a
(!!) xs 0 = head xs
(!!) xs n = (tail xs) !! (n - 1)
take :: P.Int -> Stream a -> [a]
take 0 xs = []
take n xs = (head xs) : (take (n - 1) (tail xs))
map :: (a -> b) -> Stream a -> Stream b
map f xs = f (head xs) :& map f (tail xs)
zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
zipWith f xs ys = f (head xs) (head ys) :& zipWith f (tail xs) (tail ys)
iterate :: (a -> a) -> a -> Stream a
iterate f a = a :& iterate f (f a)
函数*,-,*可以按我的要求工作,但函数否定,abs和signum不存在
GHCi, version 8.2.2: http://www.haskell.org/ghc/ :? for help
Prelude> :l Stream
[1 of 1] Compiling Stream ( Stream.hs, interpreted )
Ok, one module loaded.
*Stream> s1 = iterate (\x -> x + 1) 1
*Stream> negate s1
<interactive>:3:1: error:
• Variable not in scope: negate :: Stream P.Integer -> t
• Perhaps you meant ‘P.negate’ (imported from Prelude)
GHCi试图提供对绑定的相同访问,就像我们在加载的模块中一样。因为模块有明确的前奏导入 然后,GHCi还要求用户键入p.negate。毕竟,模块源代码也需要这样做 在GHCi中,我想也可以导入Prelude,以便再次使用所有绑定,而不必使用p..对它们进行限定,因为您没有导入Prelude否定。
GHCi, version 8.2.2: http://www.haskell.org/ghc/ :? for help
Prelude> :l Stream
[1 of 1] Compiling Stream ( Stream.hs, interpreted )
Ok, one module loaded.
*Stream> s1 = iterate (\x -> x + 1) 1
*Stream> negate s1
<interactive>:3:1: error:
• Variable not in scope: negate :: Stream P.Integer -> t
• Perhaps you meant ‘P.negate’ (imported from Prelude)
import Prelude ((+), (-), (<), (++), (*), otherwise, id)
import qualified Prelude as P