小编kap*_*kap的帖子

映射在树中的列表

我需要你的帮助来解决以下两个功能/问题:

1)

我必须替换树中的元素.树的分支可以具有任意数量的子分支,如下面的代码所示.

data Tree a = Leaf a | Branch a [(Tree a)] deriving (Show)

mapmtree :: (a -> a) -> Tree a -> Tree a
mapmtree f (Leaf a) = (f a)
mapmtree f (Branch a c) = Branch (map f a) (mapmtree f c)
Run Code Online (Sandbox Code Playgroud)

我必须通过元素并改变它们.我的问题在最后一行.mapmtree函数接受(树a)但是分支可以有一个子分支列表,因此不可能编译上面的代码,因为它给出了错误.如何在分支的子列表上调用mapmtree函数?

这是我加载时得到的错误:

Couldn't match expected type `Tree a'
           against inferred type `[Tree a]'
    In the second argument of `mapmtree', namely `c'
    In the second argument of `Branch', namely `(mapmtree f c)'
    In the …
Run Code Online (Sandbox Code Playgroud)

haskell

3
推荐指数
1
解决办法
495
查看次数

帮助解决使用警卫的问题 - 使用CODE更新

我在函数内部使用了警卫但在函数签名后没有立即使用.守卫在函数体内的do语句下.我收到此错误:

parse error on input `|'
Run Code Online (Sandbox Code Playgroud)

我想也许错误来自缩进,但我尝试了很多缩进,但我仍然得到错误.我问的是因为在功能签名之后卫兵不是立即得到错误的原因吗?

谢谢

更新1

代码:用户猜测一个数字,如果数字相同,则将数字与随机数进行比较.如果不正确,则用户将猜测直到函数中的"guess"变量为零.在每个阶段,价值(猜测)减少一个.

例如:puzz 12 5.用户可以猜测五次,随机数将在1到12之间被选中.这就是函数的假设,但它不起作用.

puzz :: Int -> Int -> IO ()
puzz boundary guess = do
                          putStr "Guess" 
                          -- putStr  -- I have to print (1 .. guess) here in each iteration
                          putStr ":"
                          x <- randomRIO (1, boundary :: Int)
                          n <- getLine
                          let
                             nTo = read n::Int
                            in print x
                               | guess == 0 = putStr "You couldn't guess right,the   correct answer is" ++ …
Run Code Online (Sandbox Code Playgroud)

haskell

1
推荐指数
1
解决办法
411
查看次数

标签 统计

haskell ×2