haskell - 为什么第二种类型的 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]
吗?
解决方案
问题只是用于获取面包屑数量的方法;一个简单(正确)的方法是:
numberOfBreadcrumbs :: FSZipper -> Int
numberOfBreadcrumbs (_, breadcrumbs) = length breadcrumbs
推荐阅读
- python - NumPy:生成包含特定元素的随机子集的最快方法
- vue.js - 如何使用 vue-tables-2 隐藏列 - Vuejs -
- javascript - JavaScript 预加载器无法正常工作
- java - 为什么我们扩展 JpaRepository 接口而不是实现它
- c# - 查看泛型类的所有特殊用途
- jquery - 显示 div 时未触发 Jquery 事件:无
- git - 主人似乎是发展的孩子
- python - 如何在 Pandas 中管理多个条件
- django - ContentType 对象的 DRF 序列化程序返回 null
- laravel - 为什么此保存功能在本地项目上有效,但在服务器和 cpanel 上无效?