Haskell: example of function of type a -> a, besides the identity

后端 未结 5 1903
情书的邮戳
情书的邮戳 2020-12-14 08:03

I\'ve just started playing a little with Haskell... I want to write a function of the same type of the identity. Obviously, not equivalent to it. That would be something lik

5条回答
  •  遥遥无期
    2020-12-14 08:36

    As others mentioned, no such other total function can exist. (If we don't limit ourselves to total functions then we can inhabit any type by undefined.)

    I'll try to give a theoretical explanation based on the λ-calculus:

    For simplicity, let's limit ourselves to λ-terms (to which we can translate any Haskell expression). For a λ-term M let's call A its head if M ≡ A N1 ... Nk and A isn't an application (k can be also zero). Note that if M is in normal form then A cannot be a λ-abstraction unless k = 0.

    So let M :: a -> a be a λ-term in normal form. Since we have no variables in the context, M cannot be a variable and it cannot be an application. If it were, its head would have to be a variable. So M must be a λ-abstraction, it must be M ≡ λ(x:a).N.

    Now N must be of type a, formally {x:a}⊢N:a. If N was a λ-abstraction, its type would be σ -> τ, which is not possible. If N was a function application then it's head would have to be a variable, and the only one we have in the context is x. But since x:a, we cannot apply x to anything, x P isn't tapeable for any P. So the only possibility is that N ≡ x. So, M must be λ(x:a).x.

    (Please correct my English, if possible. In particular, I'm not sure how to use the subjunctive right).

提交回复
热议问题