以下代码来自此tutorial
它很好地说明了如何使用" Simon-ness" (如下图所示)。我正在努力的是如何使用" Simon-ness"来修改记录中的值,比如递增" age"。我一直认为它与使用构造函数Get定义Label的方式有关。我可以添加另一个构造函数Put吗?
user.user_profile.interests = interests user.user_profile.age = age user.user_profile.save()
答案 0 :(得分:3)
在这里从臀部射击......
类Has
的功能不足以设置值。您必须添加另一个类型类函数,例如类似的东西:
class Has a l b | a l -> b where
from :: a -> Label l -> b
set :: b -> a -> Label l -> a
Person1
的定义可能如下:
instance Has Person1 "age" Int where
from (Person1 a _) _ = unField a
set v (Person1 a b) _ = Person1 (Field v) b
和incAge
函数可以这样写:
incAge :: (Num b, Has a "age" b) => a -> a
incAge pnt = let a = from pnt (Get :: Label "age")
in set (a+1) pnt (Get :: Label "age")
这可以编译,但我不确定这是否真的有用或是最好的方法。