从类型列表中获取常规列表



我找到了一种使用 ProxynatValNat转换为Integer的方法,如下面的代码所示:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Data.Proxy (Proxy)
import Data.Monoid ((<>))
import GHC.TypeLits
main :: IO ()
main = do
  fromNat (undefined :: Proxy 5)
fromNat :: KnownNat n => Proxy n -> IO ()
fromNat proxy = do
  let (num :: Integer) = natVal proxy -- converting a Nat to an Integer
  putStrLn $ "Some num: " <> show num

但是我想不出一种将类型List转换为常规列表的直接方法,下面的代码甚至没有类型检查:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Data.Proxy (Proxy)
import Data.Monoid ((<>))
import GHC.TypeLits
main :: IO ()
main = do
  fromNat     (undefined :: Proxy 5)
  fromListNat (undefined :: Proxy '[2,3,10])
fromNat :: KnownNat n => Proxy n -> IO ()
fromNat proxy = do
  let (num :: Integer) = natVal proxy -- converting a Nat to an Integer
  putStrLn $ "Some num: " <> show num
fromListNat :: Proxy [Nat] -> IO ()
fromListNat = undefined

如何将类型列表转换为常规列表?

答案是制作类似 KnownNat 但对于 Nat 的类型级别列表。我们使用类型类在类型级别列表上进行归纳。此类型类通过其超类约束,将检查列表的所有元素是否满足KnownNat,然后使用该事实重建术语级列表。

{-# LANGUAGE TypeOperators, KindSignatures #-}
-- Similar to `KnownNat (n :: Nat)`
class KnownNatList (ns :: [Nat]) where
   natListVal :: proxy ns -> [Integer]
-- Base case
instance KnownNatList '[] where
  natListVal _ = []
-- Inductive step
instance (KnownNat n, KnownNatList ns) => KnownNatList (n ': ns) where
  natListVal _ = natVal (Proxy :: Proxy n) : natListVal (Proxy :: Proxy ns)

然后,fromListNat的形状与fromNat相同:

fromListNat :: KnownNatList ns => Proxy ns -> IO ()
fromListNat proxy = do
  let (listNum :: [Integer]) = natListVal proxy
  putStrLn $ "Some list of num: " <> show listNum

将这些更改拼接到您的初始代码中,我得到了预期的输出:

$ ghc Main.hs
$ ./Main
Some num: 5
Some list of num: [2,3,10]

相关内容

  • 没有找到相关文章

最新更新