镜头如何处理脱糖字段是关键字的情况?我似乎记得读过一些特别的东西,但是我不记得我在哪里阅读它或者"镜头"访问者的名字最终会是什么.
考虑以下:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
import Control.Monad.IO.Class (liftIO)
import Data.Maybe
import Data.Aeson
import Data.Aeson.TH
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC8
import qualified Data.Text.Lazy.Encoding as TLE
data Typ = Typ {
_fld1 :: BS.ByteString
, _type :: Int
} deriving (Show)
$(deriveJSON tail ''Typ)
$(makeLenses ''Typ)
main = do
print $ typ^.fld1
print $ typ^.getType
where
jsonTyp = "{\"fld1\": \"Test\", \"type\": 1 }"
typ' = decode jsonTyp :: Maybe Typ
typ = fromJust typ'
getType :: Getter Typ Int
getType = to _type
Run Code Online (Sandbox Code Playgroud)
将_type
如何调用访问器以及如何避免在getType
此处实施?
我不得不在haskell学校打击这个,因为我在这里没有适当的开发环境,但我认为它可能对其他人有用.当我可以进入ghci并做一个:browse
(如果这给出答案)时,我会添加一个答案,但同时有人知道吗?
谢谢大家,makeLensesWith
根据爱德华的建议,我将使用关键字到替换的映射.
ham*_*mar 12
它没有做任何特别的事情.生成的镜头type
足够有名,GHC看起来非常酷.如果使用完全限定名称,甚至可以使用它:
{-# LANGUAGE TemplateHaskell #-}
module Foo where
import Control.Lens
data Bar = Bar { _type :: String }
deriving Show
$(makeLenses ''Bar)
Run Code Online (Sandbox Code Playgroud)
> :l Foo
> :t type -- Um...
<interactive>:1:1: parse error on input `type'
> :t Foo.type -- Haha!
Foo.type
:: (Functor f, Profunctor p) =>
p String (f String) -> p Bar (f Bar)
> Bar "hello" ^. Foo.type
"hello"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
425 次 |
最近记录: |