使用基于" Purescript by Example"中的示例的函数。第5章,我对如何声明多态行类型感到有点困惑。
以下编译正确
type Student = {
first :: String,
last :: String,
class :: String
}
type GymMember = {
first :: String,
last :: String,
benchPressPB :: Int
}
daveG :: GymMember
daveG = {
first: "Dave",
last: "Bro",
benchPressPB: 300
}
philS :: Student
philS = {
first : "Dave",
last : "Swat",
class : "1A"
}
schoolRollName :: forall t15.
{ last :: String
, first :: String
| t15
} -> String
schoolRollName rec = rec.last <> ", " <> rec.first
firstAndSurname :: forall t82.
{ first :: String
, last :: String
| t82
}
-> String
firstAndSurname rec = rec.first <> " " <> rec.last
daveFandS :: String
daveFandS = firstAndSurname daveG
daveSR :: String
daveSR = schoolRollName daveG
philFandS :: String
philFandS = firstAndSurname philS
philSR :: String
philSR = schoolRollName philS
但是如何删除schoolRollName和firstAndSurname的类型签名中的重复项。
我认为以下内容可行,但类型不匹配:
type NamedThing = forall t15.
{ last :: String
, first :: String
| t15
}
schoolRollName :: NamedThing -> String
schoolRollName rec = rec.last <> ", " <> rec.first
firstAndSurname :: NamedThing -> String
firstAndSurname rec = rec.first <> " " <> rec.last
-- !! Could not match type
daveFandS :: String
daveFandS = firstAndSurname daveG
答案 0 :(得分:4)
NamedThing 。要匹配 NamedThing 类型,您必须提供一个值 forall 至少第一个的可能记录和最后字段。由于 daveG 不是这样的值,编译器会抱怨 - 更进一步说这种类型没有价值。
将 t 移动到type-alias:
type NamedThing t = {first :: String, last :: String | t}
现在 firstAndSurname 必须提供带有任何额外字段的工作函数 forall NamedThings 。简单的解决方案:
firstAndSurname :: forall t. NamedThing t -> String
firstAndSurname rec = rec.first <> " " <> rec.last
最后,编译器很满意:
daveFandS :: String
daveFandS = firstAndSurname daveG