簡體   English   中英

Haskell 98下如何編寫多態函數

[英]How to code polymorphic functions under Haskell 98

作為訓練練習,我編寫了一個多態 function 來確定給定數字是單個數字還是所有數字列表的質數:

{-# LANGUAGE FlexibleInstances #-}
class PrimeTo a where
    ispt :: Integer -> a -> Bool
instance PrimeTo (Integer) where
    ispt n d = 0 /= (rem n d)
instance PrimeTo ([Integer]) where
    ispt n [] = True
    ispt n (x:xs) = (ispt n x) && (ispt n xs)

為了讓它工作,我不得不使用 FlexibleInstances,我對此很滿意,但很好奇。

據我了解,在嚴格的 Haskell 98 下,我需要在實例定義中添加一個類型描述符T

class PrimeTo a where
    ispt :: Integer -> a -> Bool
instance PrimeTo (T Integer) where
    ispt n d = 0 /= (rem n d)
instance PrimeTo (T [Integer]) where
    ispt n [] = True
    ispt n (x:xs) = (ispt n x) && (ispt n xs)

但我不知道用什么代替“T”,我什至不知道這在 Haskell 98 下是否可行。

所以:

  1. 在 Haskell 98 下這甚至可能嗎?
  2. 如果是這樣,T 會使用什么?

T可以是Integer[] ,如下所示:

class PrimeTo a where
    ispt :: Integer -> a -> Bool
instance PrimeTo Integer where
    ispt n d = 0 /= (rem n d)
instance PrimeToList a => PrimeTo [a] where
    ispt = isptList  -- see below

由於最后一個只能是[a] ,我們需要一個助手 class PrimeToList 這是額外的助手 class 和實例:

class PrimeToList a where
    isptList :: Integer -> [a] -> Bool

instance PrimeToList Integer where
    isptList n []     = True
    isptList n (x:xs) = ispt n x && isptList n xs

順便說一句,我會使用all重寫最后一個定義:

    isptList n = all (ispt n)

以上顯示了一般技術。 在您的特定情況下,您可能可以避免使用助手 class 並使用

class PrimeTo a where
    ispt :: Integer -> a -> Bool
instance PrimeTo Integer where
    ispt n d = 0 /= (rem n d)
instance PrimeTo a => PrimeTo [a] where
    ispt n = all (ispt n)

這也會定義PrimeTo [[Integer]]PrimeTo [[[Integer]]]等等,所以它不像之前的那樣完美替代。

暫無
暫無

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

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