1

我正在尝试使用 purescript-lens 来更新嵌套记录的属性。但是,当我合成镜头以到达该属性时,我收到以下类型错误:

Warning: Error at src/Main.purs line 150, column 38 - line 152, column 3: 
Error in declaration performAction
Cannot unify { description :: u24500 | u24501 } with Main.Item. Use --force to continue.

我对镜头和纯脚本比较陌生,所以它可能是简单而明显的。

产生此错误的相关代码如下(是的,它基于 purescript-thermite-todomvc):

data Action
  = NewItem String String String String String
  | RemoveItem Index
  | SetEditText String
  | DoNothing

data Item = Item
            { description :: String
            , keywords :: String
            , link_title :: String
            , profile :: String
            , title :: String
            }

data State = State
  { item :: Item
  , editText :: String
  }

_State :: LensP State { item :: _, editText :: _ }
_State f (State st) = State <$> f st

item :: forall r. LensP { item :: _ | r } _
item f st = f st.item <#> \i -> st { item = i }

editText :: forall r. LensP { editText :: _ | r } _
editText f st = f st.editText <#> \i -> st { editText = i }

itemDescription :: forall r. LensP { description :: _ | r } _
itemDescription f it = f it.description <#> \d -> it { description = d }

performAction :: T.PerformAction _ Action (T.Action _ State)
performAction _ action = T.modifyState (updateState action)
  where
  updateState :: Action -> State -> State
  updateState (NewItem s1 _ _ _ _) = _State .. item .. itemDescription .~ s1
  updateState (SetEditText s)    = _State .. editText .~ s
  updateState DoNothing          = id

我要更新的属性是 st.item.description ,上面的错误是指以“updateState (NewItem ...”开头的行。奇怪的是,下一行也报告了同样的错误。

关于如何解决类型错误的任何想法?

谢谢

4

1 回答 1

0

我通过使镜头的类型不那么通用来“解决”这个问题。我还根据 Phil 在对 purescript-lens 的“24 天”评论中使用的语法创建了镜头。我发现这种语法不那么不透明。

item :: LensP State Item
item = lens (\(State st) -> st.item) (\(State st) item -> State (st { item = item }))

editText :: LensP State String
editText = lens (\(State st) -> st.editText) (\(State st) editText -> State (st { editText = editText }))

itemDescription :: LensP Item String
itemDescription = lens (\(Item it) -> it.description) (\(Item it) description -> Item (it { description = description }))

再次,为了保持镜头类型简单,我已经去掉了_State镜头的使用performAction

performAction :: T.PerformAction _ Action (T.Action _ State)
performAction _ action = T.modifyState (updateState action)
  where
  updateState :: Action -> State -> State
  updateState (NewItem s1 _ _ _ _) = \st -> st # item..itemDescription.~ s1
  updateState (SetEditText s)    = \st -> st # editText.~ s
  updateState DoNothing          = id

我确信有一个更优雅、通用和完整的解决方案,但这必须等到我更好地理解 purescript-lens。

于 2015-01-13T12:12:53.560 回答