簡體   English   中英

Haskell:為什么這種類型檢查?

[英]Haskell: Why does this type-check?

這是一個取自Reflection-0.5的最小例子。

{-# LANGUAGE Rank2Types, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-cse -fno-full-laziness -fno-float-in #-}

import Control.Applicative
import Data.Proxy

newtype Zero = Zero Zero deriving (Show)

class ReifiesNum s where
  reflectNum :: Num a => proxy s -> a

instance ReifiesNum Zero where
  reflectNum = pure 0

在GHCi中,我得到以下內容:

>:t Zero
Zero :: Zero -> Zero

這是有道理的:我要求構造函數的類型取零並返回零。

>:t reflectNum
reflectNum :: (ReifiesNum s, Num a) => proxy s -> a

我有可能寫出類似的東西

>let x = Just (undefined::Zero)
>reflectNum x

因為類型Just Zero匹配類型變量'proxy s'。

最后,令人困惑的部分:

>:t (reflectNum Zero)
(reflectNum Zero) :: Num a => a

我不明白構造函數Zero :: Zero - > Zero的類型如何顯然匹配類型變量'proxy s',但顯然它確實是因為(reflectNum Zero)的類型只是'a'。

我很感激幫助理解這個例子,並且非常感謝與相關概念的鏈接。

謝謝

它只是函數箭頭的中綴語法,讓你失望。 首先,這是一個易於理解的案例: Maybe Int 為了使它與proxy s匹配,我們只需設置:

proxy = Maybe
s = Int

現在讓我們假裝a -> b代替寫出Fun ab ,所以Zero有類型Fun Zero Zero (即(Fun Zero) Zero )。 為了使它與proxy s匹配,我們設置:

proxy = Fun Zero
s = Zero

實際上, proxy(->) Zero ,因此proxy s((->) Zero) Zero(->) Zero ZeroZero -> Zero

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM