【问题标题】:How to make a list with all possible words in tree in haskell如何在haskell的树中列出所有可能的单词
【发布时间】:2020-01-10 07:48:46
【问题描述】:

我有

t1 = Node 'a' (Node 'c' (Node 'f' Empty Empty)
 (Node 'd' Empty Empty))                     
 (Node 'b' Empty                            
 (Node 'e' Empty Empty))                    

data BTree = Empty | Node Char BTree BTree

我需要做的函数是genWords :: BTree -> [String]

这是我目前得到的:

genWords :: BTree -> [String]
genWords Empty = []
genWords (Node ch Empty Empty) = [ch]
genWords (Node ch left right) = map (ch:) (genWords left ++ genWords right)

我知道我的错误是我使用字符并且我的函数需要返回一个字符串列表,但我不知道如何解决它。

【问题讨论】:

  • 这里的预期输出到底是什么?
  • @Chi - 返回一个空字符串列表不是有点多余吗?我的意思是,我想这取决于您是否希望输出列表包含代表树的死角的“”,但我认为这不是必需的(这取决于用例)
  • @ThomasCook 实际上,这取决于所需的输出。当我写上面的评论时,也许 OP 不想要我想到的输出。它还取决于您是想要所有根到叶路径的列表,还是根到任何节点路径的列表。
  • 实际上,根据您想要的输出,您的代码看起来不错,只是它可能应该在第二个等式中返回 [[ch]](一个字符串的列表,即单个字符长)。跨度>
  • 它应该返回 ["acf", "acd","cf", "cd", "f", "d","abe", "be", "e"]跨度>

标签: list haskell tree word


【解决方案1】:

chChar[ch]String。您可能需要 [[ch]],它是一个字符串列表 ([String])。

更详细地说,[[ch]] 是一个仅包含一个字符串的列表,该字符串为 [ch],由单个字符 ch 组成。

genWords :: BTree -> [String]
genWords Empty = []
genWords (Node ch Empty Empty) = [[ch]]
genWords (Node ch left right) = map (ch:) (genWords left ++ genWords right)

如果您也想要后缀,请尝试

genWords :: BTree -> [String]
genWords Empty = []
genWords (Node ch Empty Empty) = [[ch]]
genWords (Node ch left right) = map (ch:) subPaths ++ subPaths
   where subPaths = genWords left ++ genWords right

【讨论】:

  • 是的,这会返回 ["acf","acd","abe"] 但应该返回它应该返回 ["acf", "acd","cf", "cd", " f"、"d"、"abe"、"be"、"e"]
  • @Dontor - 我想你不太清楚你想要你的函数返回什么。您的示例返回列表不包含树中字符的每个组合吗?
  • “de”呢?我可以在您的树中找到它作为“单词”。我还可以找到其他几个不在您列表中的单词
  • @ThomasCook 我猜 OP 想要路径 (any-internal-node)-to-(any-leaf)。
  • possibleStrings :: Int -> Int -> Int possibleStrings len charCount | len == 1 = charCount | otherwise = foldl (*) start [(start + 1)..charCount] + possibleStrings (len - 1) charCount where start = charCount - (len - 1) 如果我理解正确,以上将把所有可能的字符组合成单词。因此,给定树中的 6 个字符,有 1956 个可能的单词
【解决方案2】:

我知道这个问题很老,但如果有人在这里登陆,我认为这是提问者正在寻找的解决方案:

data BTree a = Empty | Node a (BTree a) (BTree a)
  deriving Show

genWords :: BTree Char -> [String]
genWords Empty = []
genWords bTree@(Node v left right) = genRootWords bTree ++ genWords left ++ genWords right
  where genRootWords :: BTree Char -> [String]
        genRootWords Empty = []
        genRootWords (Node v Empty Empty) = [[v]]
        genRootWords (Node v left right)  = map (v:) (genRootWords left ++ genRootWords right)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2011-09-07
    • 2021-09-16
    相关资源
    最近更新 更多