豆腐实例中的模式匹配[LYAH示例]

时间:2016-01-28 09:47:05

标签: haskell pattern-matching instance typeclass type-variables

我和LYAH一起玩奇怪的豆腐示例。我通过消除Frank构造函数中的记录字段来简化它,所以这就是:

Sub FormulaFill()

Dim strFormulas(1 To 1) As Variant

With ThisWorkbook.Sheets("Export Worksheet")

strFormulas(1) = "=INDEX('sheet1'!E:E,MATCH('Export      Worksheet'!A2,'sheet1'!A:A,0))"
.Range("J1").Forumla = strFormulas(1) 

.Range("J:J").FillDown
End With

End Sub

它工作而且相当清晰。但是现在我想通过class Tofu t where tofu :: j a -> t a j data Frank a m = Frank (m a) deriving (Show) instance Tofu Frank where tofu x = Frank x 函数修改a类型的值。所以我开始在实例声明中扩展tofu的值:

x

因此我得到了:

instance Tofu Frank where
    tofu (m y) = Frank (m y)

好的,接下来我尝试在实例声明中进行实际的模式匹配:

tofu.hs:13:15: Parse error in pattern: m

因此我得到了:

instance Tofu Frank where
    tofu (Just y) = Frank (Just y)

所以,问题是:如何在豆腐的实例声明中使用类型tofu.hs:16:15: Couldn't match type `j' with `Maybe' `j' is a rigid type variable bound by the type signature for tofu :: j a -> Frank a j at tofu.hs:16:9 Expected type: j a Actual type: Maybe a In the pattern: Just y In an equation for `tofu': tofu (Just y) = Frank (Just y) In the instance declaration for `Tofu Frank' 的值?是否有可能使失败的例子在没有修改豆腐类的情况下工作?

1 个答案:

答案 0 :(得分:3)

TL; DR:你不能。

假设MyDate = #2016-2-27# MyMonth = Right("0" & Month(MyDate), 2) MyDay = Right("0" & Day(MyDate), 2) FormattedDate = Year(MyDate) & "-" & MyMonth & "-" & MyDay MsgBox FormattedDate 满足t。函数类型状态

Tofu t

实际上意味着

tofu :: j a -> t a j

因此,调用者可以选择tofu :: forall j a. j a -> t a j -- t is chosen by the class instance j。来电者可以传递a[Int]Maybe Char(此处Either String Boolj ~ Either String)。函数a ~ Bool不能假设任何特定情况,并且必须仅使用“常规”操作来完成其工作。

  

如何在豆腐的实例声明中使用类型a的值

可能没有tofu值。 E.g。

a

因为我们可以将豆腐实例化为

data T a = K Int

即使周围没有tofu :: T a -> t a T ,我们也可以在tofu (K 6 :: T Bool)中调用它。

类似的论点适用于

Bool

此处data U a = U (a -> Int) 包含一个期望U Bool的函数,而不是松散地提供或“包含”它。

相关问题