2015-01-08 36 views
6

lens ve zippers ile uğraşıyorum. Control.Monad.MonadPlus m => m (Zipper Top Int [Int] :>> A Int): kodunun altına düşünün ben gibi fermuar türünü nasıl oluşturabileceğini, data A t = A t Having ghci'to` lensi ile fermuar içine adım adım

> import Control.Lens 
> import Control.Zipper 
> 
> :t within (ix 1) $ zipper ([1,2,3] :: [Int]) 
> within (ix 1) $ zipper ([1,2,3] :: [Int]) 
    :: Control.Monad.MonadPlus m => m (Zipper Top Int [Int] :>> Int) 

çalıştırmak?

Ben within (ix 1 . to A) $ zipper ([1,2,3] :: [Int]) çalıştım ama bir hata veriyor:

Could not deduce (Contravariant 
        (Bazaar (Indexed Int) (A Int) (A Int))) 
    arising from a use of ‘to’ 
from the context (Control.Monad.MonadPlus m) 
    bound by the inferred type of 
      it :: Control.Monad.MonadPlus m => 
       m (Zipper Top Int [Int] :>> A Int) 
    at Top level 
In the second argument of ‘(.)’, namely ‘to A’ 
In the first argument of ‘within’, namely ‘(ix 1 . to A)’ 
In the expression: within (ix 1 . to A) 

cevap

2

bir yolu bir Iso yapmak ve bununla oluşturmak etmektir.

> import Control.Lens 
> import Control.Zipper 
> 
> data A t = A t 
> let _A = iso A (\(A a) -> a) 
> 
> let a = within (ix 1 . _A) $ zipper ([1,2,3] :: [Int]) 
> :t a 
a :: MonadPlus m => m (Zipper Top Int [Int] :>> A Int) 
> a ^? _Just . focus 
Just (A 2) 

Düzenleme:: GHCi olarak sebeple size (\(A a) -> a) böylece buradan geri alabilirsiniz olduğunu gerekir.

> data A t = A t 
> let _A = iso A (error "Can't unA") 
> 
> let a = within (ix 1 . _A) $ zipper ([1,2,3] :: [Int]) 
> a ^? _Just . focus 
Just (A 2) 
> fmap upward a ^? _Just . focus 
Just [1,*** Exception: Can't unA 

Ben A ayıklanması için bir fonksiyonu olmadan bu hale getirmek için geçerli bir yolu var sanmıyorum. `Specyfing olmadan bunu yapmak için herhangi bir yolu var mı

> data A t = A t 
> let _A f a = a <$ f (A a) 
> 
> let a = within (ix 1 . _A) $ zipper ([1,2,3] :: [Int]) 
> let b = a & _Just . focus .~ A 10 
> b ^? _Just . focus 
Just (A 10) 
> fmap upward b ^? _Just . focus 
Just [1,2,3] -- Should be Just [1, 10, 3] 
+0

(\ (A) -> a)' fonksiyonu: Geçersiz bir Traversal yazabiliriz ama yine de düzgün çalışmaz? Burada sadece undefined 'geçebilir miyim eğer benim durumumda bu açık değil mi? – remdezx

+0

Gerçekten değil. Sorun, geri dönemeyeceksin. Geri almak için 'yukarı 'yi kullanmak bir' undefined 'verecekti. – cchalmers

+1

Anladım ... "Iso" dan başka seçenek var mı? – remdezx