【问题标题】:Find values in a tree - type checking SML在树中查找值 - 类型检查 SML
【发布时间】:2018-07-28 12:37:51
【问题描述】:

我需要编写我自己的数据类型 - 和 anyTree,它们都有自己的类型。有了这些,我需要创建一个函数,它接受一个 int 和一个 anyTree 作为参数,它在树中搜索,如果值存在于树中则返回 true。类型必须是:everyTree -> int -> bool

到目前为止我有:

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 相互转换,以便我可以比较它们。谁有想法? 谢谢。

【问题讨论】:

    标签: types tree pattern-matching sml smlnj


    【解决方案1】:

    您可以对整个参数使用模式匹配;您不需要将自己限制在最外层的构造函数中。

    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
    

    是一种很迂回的写法E

    if E1 then true else E2
    

    通常写成

    E1 orelse E2
    

    您永远不需要将布尔值与truefalse 进行比较——e = true 等效于ee = false 等效于not e

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2016-01-22
      • 2011-04-12
      • 2015-01-03
      • 2012-10-29
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多