tôi có các module sau:Làm thế nào để chứng minh sự phủ định kép cho các boolean mức loại?
{-# LANGUAGE DataKinds, KindSignatures, TypeFamilies, RoleAnnotations #-}
module Main where
import Data.Coerce (coerce)
-- logical negation for type level booleans
type family Not (x :: Bool) where
Not True = False
Not False = True
-- a 3D vector with a phantom parameter that determines whether this is a
-- column or row vector
data Vector (isCol :: Bool) = Vector Double Double Double
type role Vector phantom
-- convert column to row vector or row to column vector
flipVec :: Vector isCol -> Vector (Not isCol)
flipVec = coerce
-- scalar product is only defined for vectors of different types
-- (row times column or column times row vector)
sprod :: Vector isCol -> Vector (Not isCol) -> Double
sprod (Vector x1 y1 z1) (Vector x2 y2 z2) = x1*x2 + y1*y2 + z1*z2
-- vector norm defined in terms of sprod
norm :: Vector isCol -> Double
-- this definition compiles
norm v = sqrt (v `sprod` flipVec v)
-- this does not (without an additional constraint, see below)
norm v = sqrt (flipVec v `sprod` v)
main = undefined
Định nghĩa thứ hai của norm
không biên dịch, vì flipVec v
lợi nhuận Vector (Not isCol)
và do đó sprod
muốn một Vector (Not (Not isCol))
như là đối số thứ hai:
Main.hs:22:34:
Couldn't match type ‘isCol’ with ‘Not (Not isCol)’
‘isCol’ is a rigid type variable bound by
the type signature for norm :: Vector isCol -> Double
at Main.hs:20:9
Expected type: Vector (Not (Not isCol))
Actual type: Vector isCol
Relevant bindings include
v :: Vector isCol (bound at Main.hs:22:6)
norm :: Vector isCol -> Double (bound at Main.hs:22:1)
In the second argument of ‘sprod’, namely ‘v’
In the first argument of ‘sqrt’, namely ‘(flipVec v `sprod` v)’
tôi có thể tất nhiên thêm ràng buộc isCol ~ Not (Not isCol)
đến loại norm
:
norm :: isCol ~ Not (Not isCol) => Vector isCol -> Double
Tại trang web cuộc gọi, giá trị thực tế của isCol
được biết và trình biên dịch sẽ thấy ràng buộc này thực sự hài lòng. Nhưng có vẻ lạ khi chi tiết triển khai của norm
bị rò rỉ vào chữ ký loại.
Câu hỏi của tôi: có thể bằng cách nào đó thuyết phục trình biên dịch rằng isCol ~ Not (Not isCol)
luôn đúng, do đó hạn chế thừa không cần thiết?
Awesome, cảm ơn bạn! –
Nó hơi không hài lòng khi chúng ta không thể loại bỏ ràng buộc (không gian lận) mặc dù có vẻ như chúng ta thực sự không cần từ điển khi chạy. Có lý do cơ bản nào cho việc này không? Hoặc cần phải cải thiện loại GHC nào để tránh hạn chế? –
Đó là một sự bình đẳng theo mệnh đề nên nó vẫn đòi hỏi bằng chứng (tầm thường). –