0
我建立了基本的參數化多態性的簡單的類接口:理解String對[Char]的影響?
class Document a where
present :: a -> b -> Bool
instance Document String where
present s o = False
instance Document Int where
present i o = True
implementation :: Document a => a -> Int -> Bool
implementation v int | int > 10 = present v
| otherwise = False
我明白,當數值參數的參數由Document
限制你必須指定其類型:
print $ implementation (22 :: Int) 400
我的理解這是由於編譯器不知道22是否是Int
或Float
。
不過,我看,這同樣適用於字符串:
print $ implementation ("mystring" :: String) 400
再次,String
和[Char]
區分。但是我實際上並不瞭解這些之間的實際差異?
我認爲Haskell的編譯器行爲與C/C++類似,其中所有類型的String
在編譯時轉換爲[Char]
- 這是不是這種情況?
爲什麼會用而不是String
,反之亦然?
沒有區別; 'String'正好是'[Char]',被定義爲'type String = [Char]'。不過,字符串文字可以用'OverloadedStrings'擴展名重載。 – Ryan
你有另一個錯誤:'目前v :: b - >布爾',而不是'布爾'。 – chepner