[英]Associate a type level optional natural number (Maybe Nat) with a value
function natVal:: forall n proxy. KnownNat n => proxy n -> Integer
natVal:: forall n proxy. KnownNat n => proxy n -> Integer
將類型級別 natural 與Integer
值相關聯。 使用DataKinds
, TypeApplications
語言擴展可以做
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeApplications #-}
module Derp where
import Data.Proxy ( Proxy(..) )
import GHC.TypeLits ( natVal )
foo :: Integer
foo = natVal (Proxy @1337)
如何將'Maybe Nat
與某個值相關聯? 例如, Maybe Integer
foo2 :: Maybe Integer
foo2 = maybeNatVal (Proxy @(Just 1337))
這就是單例 package 所做的。 相關的 function 被命名為demote
。 demote
,專用於類型級值(具有可見類型應用程序),等於相應的術語級值。
需要提及的一個區別是Nat
降級為Natural
。
{-# LANGUAGE TypeApplications, DataKinds #-}
import Data.Singletons
import Numeric.Natural (Natural) -- base
myexample :: Maybe Natural
myexample = demote @('Just 1337)
我們總是使用相同的東西將類型轉換為值:類型類。
class MaybeNatVal (v :: Maybe Nat) where
maybeNatVal :: Proxy v -> Maybe Integer
instance MaybeNatVal Nothing where
maybeNatVal _ = Nothing
instance KnownNat n => MaybeNatVal (Just n) where
maybeNatVal x = Just $ natVal $ unJust x
where unJust :: Proxy (Just n) -> Proxy (n :: Nat)
unJust _ = Proxy
另一個答案中建議的庫做同樣的事情,除了類型類是多態的並且實例是由模板 Haskell 生成的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.