OCaml: Match expression inside another one?

后端 未结 2 1492
孤街浪徒
孤街浪徒 2020-12-24 05:18

I\'m currently working on a small project with OCaml; a simple mathematical expression simplifier. I\'m supposed to find certain patterns inside an expression, and simplify

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 05:51

    You can make this terser (and I would argue clearer) by judicious use of underscores, as's and or-patterns. The resulting code is also more efficient, because it allocates less (in the Var, Sum and Prod cases)

    let rec filter = function
    | Var _ | Sum _ | Prod _ as e -> e
    | Diff (_, (Sum _ | Diff _) as e) -> filter (diffRule e)
    | Diff (_,e) -> e
    | Quot (_, (Quot _| Prod _) as e) -> filter (quoteRule e)
    | Quot (_,e) -> filter e
    ;;
    

提交回复
热议问题