What are nonlinear patterns

前端 未结 1 949
离开以前
离开以前 2021-01-12 19:27

I am reading the paper about the servant-api DSL (see pdf here)

Quoting from Section 5.2 Type safe Links (emphasize added by me)

1条回答
  •  独厮守ぢ
    2021-01-12 20:16

    A linear pattern is a patter where each variable appears at most one.

    A non-linear pattern allows reusing the same variable name implying that all the values matched by it must be equal.

    What the documentation is saying is that non linear patterns are accepted in type families definitions while they are not in normal function definitions:

    Prelude> let f x x = x
    
    :2:7:
        Conflicting definitions for ‘x’
        Bound at: :2:7
                  :2:9
        In an equation for ‘f’
    

    There's nothing "deep" in this. There are other languages which allow "non linear" patterns in function definitions (e.g. Curry).

    So: no, type constructors have nothing to do with linearity/non linerity. Is just how you use variables in the pattern matching.


    As to why Haskell doesn't have non linear patterns for function definitions: there are cons. For example what should \x x -> x mean? \x -> \x -> x? Or \x y | x == y -> x?

    Also f x x = 1 would not be a total function. There's an hidden guard, and thus f [1..] [1..] would loop forever instead of simply returning 1.


    As has been pointed out in the comments, the linear term may come from linear logic. This logic has a "resource interpretation" where, fundamentally, implication "consumes" its antecedent in order to produce the consequent.

    In its sequent calculus you cannot reuse an hypothesis multiple times as you do in classical logic. This is akin to linear patterns: you cannot reuse the same variable multiple times. Follow-up question: why is linear logic called linear logic? No idea.

    0 讨论(0)
提交回复
热议问题