gpt4 book ai didi

Haskell - 为什么我不在范围内 : data constructor ‘ZipList’ error

转载 作者:行者123 更新时间:2023-12-04 07:18:29 26 4
gpt4 key购买 nike

我正在从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]

要定义你自己的,你必须定义一个新的 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 .

关于Haskell - 为什么我不在范围内 : data constructor ‘ZipList’ error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68650377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com