繁体   English   中英

重现 Haskell 镜头教程的问题

[英]issues reproducing Haskell lens tutorial

我觉得我做错了什么,因为我什至没有设法重现 Haskell 的lens教程

> import Control.Lens
> data Point = Point { _x :: Double, _y :: Double } deriving (Show)
> data Atom = Atom { _element :: String, _point :: Point } deriving (Show)
> point = lens _point (\atom newPoint -> atom { _point = newPoint })
> :t point
point :: Functor f => (Point -> f Point) -> Atom -> f Atom
> point :: Lens' Atom Point = lens _point (\atom newPoint -> atom { _point = newPoint })

<interactive>:6:10: error:
    • Illegal polymorphic type: Lens' Atom Point
      Perhaps you intended to use RankNTypes or Rank2Types
    • In a pattern type signature: Lens' Atom Point
      In the pattern: point :: Lens' Atom Point
      In a pattern binding:
        point :: Lens' Atom Point
          = lens _point (\ atom newPoint -> atom {_point = newPoint})
> :set -XRankNTypes
> point :: Lens' Atom Point = lens _point (\atom newPoint -> atom { _point = newPoint })

<interactive>:8:29: error:
    • Couldn't match type ‘(Point -> f0 Point) -> Atom -> f0 Atom’
                     with ‘forall (f :: * -> *).
                           Functor f =>
                           (Point -> f Point) -> Atom -> f Atom’
      Expected type: Lens' Atom Point
        Actual type: (Point -> f0 Point) -> Atom -> f0 Atom
    • In the expression:
        lens _point (\ atom newPoint -> atom {_point = newPoint})
      In a pattern binding:
        point :: Lens' Atom Point
          = lens _point (\ atom newPoint -> atom {_point = newPoint})

它肯定似乎看到了f0Functor f之间的一些差异。

不过,我在这里的代码与教程中的代码没有什么不同,据我所知,似乎没有多少扩展可以拯救我。

可能有人有任何指示吗?

我在评论中证实了这个猜测。 这是因为您将类型放入模式匹配中。 它可能是一个简单的模式匹配,但它是一个模式匹配,因为它在=的 LHS 上绑定了一个名称。

在 Haskell 中默认甚至不允许这样做。 在 GHC 中,您需要在允许之前启用 ScopedTypeVariables 扩展。 当你这样做时,它对多态性产生了奇怪的影响。 我不了解该功能与高级多态性之间的所有交互,但它绝对是单态化类型并期望它是多态性的。 那是行不通的。

如果您将类型本身的名称与值绑定在一起,我强烈建议您仅将类型放入模式中。 有时在处理存在主义时会出现这种情况,但我从未见过在其他任何情况下都会出现这种情况。

否则,只需使用普通的类型归属语法,即使您必须加入几个分号才能使其在 ghci 中工作:

point :: Lens' Atom Point ; point = lens _point (\atom newPoint -> atom { _point = newPoint })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM