我目前正在為即將到來的考試而學習。
我們得到了一些用于準備和培訓的功能。
如果確切的 2 個節點具有相同的值,我想要一個函式給出 True。
鑒于:
data Tree a = Node a [Tree a] | Leaf a
exercise62 :: Eq a => Tree62 a -> Bool
exercise62 = undefined
exercise62 (Node 5 [Node 6 [Leaf 4], Node 4 [Leaf 3]]) ~> True
exercise62 (Node 5 [(Node 5 [Leaf 4])]) ~~> True
exercise62 (Node 5 [Node 6 [Leaf 4], Node 3 [Leaf 2]]) ~~> False
我的想法是:
1.)創建一個函式,它將給出一個包含所有值的串列。
2.)檢查是否有一個值出現兩次。
我的問題是1。)
到目前為止我嘗試了什么:
exercise62Helper :: Eq a => Tree a -> [a]
exercise62Helper (Leaf a) = [a]
exercise62Helper (Node a b) = [a] exercise62Helper (head b)
我認為我的問題是exercise62Helper (head b)因為我只檢查串列的第一個元素而不是 [Tree a] 中的所有元素。
但我不明白如何準確訪問它們,通常我會通過 tail 訪問它們,但這是不可能的(或者我不知道),因為函式的引數是Tree而不是[Tree]
uj5u.com熱心網友回復:
您可以使用映射overconcatMap :: Foldable f => (a -> [b]) -> f a -> [b]的所有元素,并連接結果。您的函式也不需要型別約束,因為無論您是否可以檢查兩個專案是否相等,您都可以列出這些專案:bexercise62HelperEq a
exercise62Helper :: Tree a -> [a]
exercise62Helper (Leaf a) = [a]
exercise62Helper (Node a b) = a : concatMap exercise62Helper b
您還可以使用DeriveFoldable擴展,讓 HaskellFoldable為您的型別生成一個簡單的實體:
{-# LANGUAGE DeriveFoldable #-}
data Tree a = Node a [Tree a] | Leaf a deriving Foldable
然后exercise62Helper是一個特殊版本toList :: Foldable f => f a -> [a]:
import Data.Foldable(toList)
exercise62Helper :: Tree a -> [a]
exercise62Helper = toList
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437508.html
上一篇:從SQLite正確選擇以前的日期
下一篇:層“conv2d_transpose_4”的輸入0與層不兼容:預期ndim=4,發現ndim=2。收到的完整形狀:(無,100)
