如何将字段构造函数参数传递给函数?

时间:2014-05-01 06:53:08

标签: haskell lens

1)我需要将一个字段构造函数参数传递给一个函数。我做了一些测试,但我无法做到。可能吗?否则,是否可以使用镜头包?

2)MonadState中是否可以使用modify修改字段? (我做了几次尝试,但没有成功。例如:modify(second =“x”)不起作用。

import Control.Monad.State

data Test = Test {first :: Int, second :: String} deriving Show

dataTest = Test  {first = 1, second = ""}

test1 = runStateT modif1 dataTest -- OK

test2 = runStateT (modif2 "!") dataTest -- OK

test3 = runStateT (modif3 second) dataTest -- WRONG


-- modif1 :: StateT Test IO ()
modif1 = do
  st <- get
  r <- lift getLine
  put $ st {second = "x" ++ r} 


-- modif2 :: String -> StateT Test IO ()
modif2 s = do
  stat <- get
  r <- lift getLine
  put $  stat {second = "x" ++ r ++ s}

-- modif3 :: ???? -> StateT Test IO ()
modif3 fc = do
  stat <- get
  r <- lift getLine
  put $  stat {fc = "x" ++ r}

-- When i try to load the module, this is the result:
-- ghc > Failed:
--  ProvaRecord.hs:33:16:`fc' is not a (visible) constructor field name

1 个答案:

答案 0 :(得分:4)

正如你所说,你可能正在寻找镜头。镜头是允许读取,设置或修改给定字段的值。通常使用Control.Lens,您可以使用下划线定义字段,并使用makeLenses创建功能齐全的镜头。

有许多组合器允许镜头在MonadState内一起使用。在您的情况下,我们可以使用%=,在这种情况下,它将专门用于输入

(MonadState s m) => Lens' s b -> (b -> b) -> m ()

使用给定镜头和对内部值进行操作的函数修改状态值。

您的示例可以使用镜头重写如下:

{-# LANGUAGE TemplateHaskell, RankNTypes #-}
import Control.Lens
import Control.Monad.State

data Test = Test { _first :: Int
                 , _second :: String
                 }
    deriving Show

-- Generate `first` and `second` lenses.
$(makeLenses ''Test)

-- | An example of a universal function that modifies any lens.
-- It reads a string and appends it to the existing value.
modif :: Lens' a String -> StateT a IO ()
modif l = do
    r <- lift getLine
    l %= (++ r)


dataTest :: Test
dataTest = Test  { _first = 1, _second = "" }

test :: IO Test
test = execStateT (modif second) dataTest