簡體   English   中英

創建數據類型列表Haskell

[英]Creating a data type list Haskell

我已經在Haskell中完成了一個個人列表,如下所示:(2,(1,1),3)->列表[數字2,列表[數字1,數字1],列表[數字3]]。

這是我的方法:

data SList a = Num a | List [SList a] deriving Show
emptySList :: SList a
emptySList = (List [])

consElem :: a -> SList a -> SList a
consElem x (List y) = (List ((Num x) : y))

consList :: SList a -> SList a -> SList a
consList a b = (List [a,b])

我設法使用consElem和consList來形成此列表(列表[Num 2,列表[Num 1,Num 1],列表[Num 3]]),如下所示:

consElem 2 $ consList (consElem 1 $ consElem 1 emptySList) $ consElem 3 emptySList

我想知道如何在常規列表中轉換SList。 例如,如果我有此SList: List [Num 2, List [Num 1, Num 1], List [Num 3]]它應該變為[2,1,1,3]

我的嘗試:

atomToNormal x
    | null x = []
    | otherwise = slistToList (head x) ++ atomToNormal (tail x)
slistToList :: SList a -> [a]
slistToList (List x) = atomToNormal x
slistToList (Num x) = [x]

GHC實際上可以為您編寫此功能:

{-# LANGUAGE DeriveFoldable #-}
import Data.Foldable as Foldable

data SList a = Num a | List [SList a]
  deriving (Show, Foldable)

slistToList :: SList a -> [a]
slistToList = Foldable.toList

如果您想自己做–我不太明白atomToNormal應該做什么,那么您就不需要它。 只需在slistToList解構樹分支列表 head-first slistToList

slistToList :: SList a -> [a]
slistToList (Num x) = _
slistToList (List []) = _
slistToList (List (l:ls)) = _

現在填補空白。 GHC(> = 7.10)也可以為您提供很多幫助:只需嘗試使用下划線空白按原樣編譯,它將告訴您

/tmp/wtmpf-file17703.hs:8:23:
    Found hole ‘_’ with type: [a]
    Where: ‘a’ is a rigid type variable bound by
               the type signature for slistToList :: SList a -> [a]
               at /tmp/wtmpf-file17703.hs:7:16
    Relevant bindings include
      x :: a (bound at /tmp/wtmpf-file17703.hs:8:18)
      slistToList :: SList a -> [a]
        (bound at /tmp/wtmpf-file17703.hs:8:1)
    In the expression: _
    In an equation for ‘slistToList’: slistToList (Num x) = _

因此,第一個間隙必須具有[a]類型,並且唯一的值是x::a 好吧,您可以將其包裝在單例列表中

slistToList (Num x) = [x]

與其他子句的處理方式相同。 根據經驗,如果僅以某種方式包括所有“相關綁定”(通常,只有一種方法可以做到這一點),那么您的實現可能是正確的。

當然,這僅在您首次寫出類型簽名時才有效…… 無論如何 ,這始終應該是您要做的第一件事


您的類型確實應該叫樹狀,而不是SList

暫無
暫無

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

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