haskell - Haskell - 为什么我不在范围内:数据构造函数“ZipList”错误
问题描述
我正在从 learn-you-a-haskell 书中学习 Haskell 中的应用函子。但是每当我尝试在 ghci 中输入以下代码时:
:{
instance Applicative ZipList where
pure x = ZipList (repeat x)
ZipList fs <*> ZipList xs = ZipList (zipWith (\f x -> f x) fs xs)
:}
我得到三个错误:
<interactive>:137:22: error:
Not in scope: type constructor or class ‘ZipList’
<interactive>:139:9: error:
Not in scope: data constructor ‘ZipList’
<interactive>:139:24: error:
Not in scope: data constructor ‘ZipList’
我尝试加载:
import Data.List
import Data.Char
我尝试搜索 ZipList 没有成功。
我尝试在没有实例声明的情况下运行接下来的几个表达式:
getZipList $ (+) <$> ZipList [1,2,3] <*> ZipList [100,100,100]
但它们也因以下错误而失败:
<interactive>:142:1: error:
Variable not in scope: getZipList :: f0 Integer -> t
<interactive>:142:22: error:
Data constructor not in scope: ZipList :: [Integer] -> f0 Integer
<interactive>:142:42: error:
Data constructor not in scope: ZipList :: [Integer] -> f0 Integer
我也尝试搜索并找到了这个答案: Haskell ZipList Applicative 但这对我没有帮助。
解决方案
ZipList
已经存在Control.Applicative
并使用Applicative
那里定义的实例。您无法重新定义该实例。
>> import Control.Applicative
>> getZipList $ (+) <$> ZipList [1,2,3] <*> ZipList [100,100,100]
[101,102,103]
>> getZipList $ liftA2 (+) (ZipList [1,2,3]) (ZipList [100,100,100])
[101,102,103]
要定义你自己的,你必须定义一个我们读为“ prime”的新的: ZipList'
ZipList
-- >> getZipList' $ (+) <$> ZipList' [1,2,3] <*> ZipList' [100,100,100]
-- [101,102,103]
newtype ZipList' a = ZipList' { getZipList' :: [a] }
instance Functor ZipList' where
fmap f (ZipList' as) = ZipList' (fmap f as)
instance Applicative ZipList' where
pure a = ZipList' (repeat a)
ZipList' fs <*> ZipList' xs = ZipList' (zipWith (\f x -> f x) fs xs)
也可以导出Functor
。fmap
我建议为, pure
,编写实例签名(<*>)
:
{-# Language DeriveFunctor #-}
{-# Language DerivingStrategies #-}
{-# Language InstanceSigs #-}
import Control.Applicative (liftA2)
newtype ZipList' a = ZipList' { getZipList' :: [a] }
deriving
stock Functor
-- instance Functor ZipList' where
-- fmap :: (a -> a') -> (ZipList' a -> ZipList' a')
-- fmap f (ZipList' as) = ZipList' (fmap f as)
instance Applicative ZipList' where
pure :: a -> ZipList' a
pure a = ZipList' (repeat a)
(<*>) :: ZipList' (a -> b) -> ZipList' a -> ZipList' b
ZipList' fs <*> ZipList' xs = ZipList' (zipWith ($) fs xs)
liftA2 :: (a -> b -> c) -> (ZipList' a -> ZipList' b -> ZipList' c)
liftA2 (·) (ZipList' as) (ZipList' bs) = ZipList' (zipWith (·) as bs)
你可以(\f x -> f x)
写成($)
或id
。
推荐阅读
- json - WSO2 Governance Registry 的 Governance REST API - POST 字段数组
- java - Spring Data JPA表连接创建运算符不存在错误
- mysql - 插入临时表在mysql存储过程中不起作用
- python - 如何使用 TensorFlow 解码存储在 tfrecords 中的字节列表?
- matlab - 在 Matlab 中绘制具有不同(独立)限制的 x 轴和 y 轴
- java - 使用递归时如何正确添加字符串
- c++ - C ++将数据从文本文件读取到结构数组中
- java - 用于 FHIR 的 JSON 模式到 Java 类
- java - 使用 snakeYaml 解析字符串数组
- reactjs - React 16.7 有 State Hook,所以我不再需要 react-redux,对吗?