ツリーの各要素に異なる値(Intなど)を付けたいとします。私はこれを行うことができましたが、コードは獣としては醜いですし、モナドとのやり方もまだ分かりません。Haskellでツリーを飾る方法
私のテイク:
data Tree a = Tree (a, [Tree a])
tag (Tree (x, l)) n = ((m, x), l')
where (m,l') = foldl g (n,[]) l
where g (n,r) x = let ff = tag x n in ((fst $ fst ff) +1, (Tree ff):r)
はあなたには、いくつかのより良い方法を知っていますか?
編集: 私は、上記のfoldlが本当にmapAccumLであることに気付きました。私は少しあなたのタイプを変更した
import Data.List (mapAccumL)
data Tree a = Tree (a, [Tree a])
tag (Tree (x, l)) n = ((m,x),l')
where (m,l') = mapAccumL g n l
g n x = let [email protected]((f,_),_) = tag x n in (f+1,ff)
注意をnewtypesを削除すると、状態モナドのmapMしたがって、mapAccumLを使用するたびに、状態モナドの使用を検討してください。 –