functional programming - Match Comparison OCaml -
i have come love syntax in ocaml
match mycompare x y |greater-> |less-> |equal->
however, needs 2 things, custom type, , mycompare function returns custom type.
would there anyway without doing steps above?
the pervasives module seems have 'compare' returns 0 if equal, pos int when greater , neg int when less. possible match those? conceptually (which not compile):
match mycompare x y | (>0) -> | (0) -> | (<0) ->
i know use if statements, pattern matching more elegant me. there easy (if not maybe standard) way of doing this?
is there easy … way of doing this?
no!
the advantage of match
on switch
in language ocaml's match
tells if have thought of covering cases (and allows match in-depth , compiled more efficiently, considered advantage of types). lose advantage of being warned if stupid, if started using arbitrary conditions instead of patterns. end construct same drawbacks switch
.
this said, actually, yes!
you can write:
match mycompare x y | z when (z > 0) -> 0 | 0 -> 0 | z when (z < 0) -> 0
but using when
makes lose advantage of being warned if stupid.
the custom type type comparison = greater | less | equal
, pattern-matching on 3 constructors right way. documents mycompare
instead of letting return int
also, in language, represent file descriptor. type definitions not have run-time cost. there no reason not use 1 in example.
Comments
Post a Comment