In Functional Programming, is it considered a bad practice to have incomplete pattern matchings

前端 未结 7 1375
梦毁少年i
梦毁少年i 2020-12-09 02:12

Is it generally considered a bad practice to use non-exhaustive pattern machings in functional languages like Haskell or F#, which means that the cases specified don\'t cove

7条回答
  •  醉话见心
    2020-12-09 02:32

    This question has two aspects.

    1. For the user of the API, failwith... simply throws a System.Exception, which is unspecific (and therefore is sometimes considered a bad practice in itself). On the other hand, the implicitly thrown MatchFailureException can be specifically caught using a type test pattern, and therefore is preferrable.
    2. For the reviewer of the implementation code, failwith... clearly documents that the implementer has at least given some thought about the possible cases, and therefore is preferrable.

    As the two aspects contradict each other, the right answer depends on the circumstances (see also kvb's answer). A solution which is 100% "correct" from any point of view would have to

    • deal with every case explicitly,
    • throw a specific exception where necessary, and
    • clearly document the exception

    Example:

    /// Gets the first element of the list.
    /// The list is empty.
    let head list = 
        match list with
        | [] -> invalidArg "list" "The list is empty." 
        | x::xs -> x
    

提交回复
热议问题