Types 在树类型检查SML中查找值
我需要编写自己的数据类型——或者,或者,eitherTree,它们有自己的类型。有了这些,我需要创建一个函数,以int和eitherTree作为参数,在树中搜索,如果树中存在值,则返回true。类型必须为:eitherTree->int->bool 到目前为止,我已经:Types 在树类型检查SML中查找值,types,tree,pattern-matching,sml,smlnj,Types,Tree,Pattern Matching,Sml,Smlnj,我需要编写自己的数据类型——或者,或者,eitherTree,它们有自己的类型。有了这些,我需要创建一个函数,以int和eitherTree作为参数,在树中搜索,如果树中存在值,则返回true。类型必须为:eitherTree->int->bool 到目前为止,我已经: datatype either = ImAString of string | ImAnInt of int datatype eitherTree = eLEAF of either | eINTERIOR of (eithe
datatype either = ImAString of string | ImAnInt of int
datatype eitherTree = eLEAF of either | eINTERIOR of (either*eitherTree*eitherTree)
fun eitherSearch v1 (eLEAF((v2)) = if v1 = v2 then true
else false
| eitherSearch v1 (eINTERIOR(e1, et1, et2)) = if v1 = e1 then true
else if (eitherSearch v1 et1) = true
then true
else if (eitherSearch v1 et1) = true
then true else false
“技巧”似乎是将ImAnInt/int相互转换,以便我可以比较它们。有人有什么想法吗?
谢谢。您可以对整个参数使用模式匹配;您不需要将自己限制在最外层的构造函数中
fun eitherSearch v1 (eLEAF (ImAnInt v2)) = v1 = v2
| eitherSearch v1 (eLEAF _) = false
| ...
或者您可以编写一个比较函数:
fun equalInt (v, ImAnInt v') = v = v'
| equalInt _ = false
fun eitherSearch v1 (eLEAF v2) = equalInt(v1, v2)
| ...
另一方面
if E then true else false
是一种非常迂回的书写方式
if E1 then true else E2
通常是书面的
E1 orelse E2
而且您不需要将布尔值与true
或false
进行比较–e=true
相当于e
,e=false
相当于而不是e