首页 > 解决方案 > 为什么第二种类型的 Zipper 是数据列表而不是纯数据?

问题描述

我通过Learn your Haskell上的教程完成了自己的工作 ,我问自己为什么作者使用列表作为实现 Zipper 的第二种类型?

这是相关的代码:

type Name = String
type Data = String
data FSItem = File Name Data
    | Folder Name [FSItem]
    deriving (Show)

data FSCrumb = FSCrumb Name [FSItem] [FSItem]
    deriving (Show)
type FSZipper = (FSItem, [FSCrumb])

-- -------------------------------------------------------------------------------
-- Some other code he uses
-- -------------------------------------------------------------------------------

fsUp :: FSZipper -> FSZipper
fsUp (item, FSCrumb name ls rs : bs) = (Folder name (ls ++ [item] ++ rs), bs)

fsTo :: Name -> FSZipper -> FSZipper
fsTo name (Folder folderName items, bs) =
    let (ls, item:rs) = break (nameIs name) items
    in  (item, FSCrumb folderName ls rs:bs)

nameIs :: Name -> FSItem -> Bool
nameIs name (Folder folderName _) = name == folderName
nameIs name (File   fileName   _) = name == fileName

x -: f = f x

-- -------------------------------------------------------------------------------
-- Example to work on
-- -------------------------------------------------------------------------------

myDisk :: FSItem  
myDisk = 
    Folder "root"   
        [ File "goat_yelling_like_man.wmv" "baaaaaa"  
        , File "pope_time.avi" "god bless"  
        , Folder "pics"  
            [ File "ape_throwing_up.jpg" "bleargh"  
            , File "watermelon_smash.gif" "smash!!"  
            , File "skull_man(scary).bmp" "Yikes!"  
            ]  
        , File "dijon_poupon.doc" "best mustard"  
        , Folder "programs"  
            [ File "fartwizard.exe" "10gotofart"  
            , File "owl_bandit.dmg" "mov eax, h00t"  
            , File "not_a_virus.exe" "really not a virus"  
            , Folder "source code"  
                [ File "best_hs_prog.hs" "main = print (fix error)"  
                , File "random.hs" "main = print 4"  
                ]  
            ]  
        ] 

您可以使用的命令:

*Filesystem> let newFocus1 = (myDisk,[]) -: fsTo "programs" -: fsTo "source code"
*Filesystem> let newFocus2 = (myDisk,[]) -: fsTo "pics" -: fsTo "ape_throwing_up.jpg"

无论我做什么,我总是会得到一个只有一个项目的列表,所以使用 justFSCrumb而不是 不是更好[FSCrumb]吗?

标签: haskellzipper

解决方案


问题只是用于获取面包屑数量的方法;一个简单(正确)的方法是:

numberOfBreadcrumbs :: FSZipper -> Int
numberOfBreadcrumbs (_, breadcrumbs) = length breadcrumbs

推荐阅读