Haskell使用map调用具有多个参数的函数

时间:2020-01-24 15:28:07

标签: haskell

假设我们有以下表示二进制树的代码,其中decodeInt在树中搜索整数:

import Text.Show.Functions
data BinTree a b = Leaf b | Node a (BinTree a b) (BinTree a b) deriving Show

example :: BinTree (Int -> Bool) Char
example = Node (\x -> x > 4) (Node (\x -> x * x == x) (Leaf 'g') (Node (\x -> x == 0)
          (Leaf 'u') (Leaf 'l'))) (Node (\x -> x >= 7) (Leaf 'f') (Leaf 'i'))

countInnerNodes :: BinTree a b -> Int
countInnerNodes (Node a b c) = 1 + countInnerNodes b + countInnerNodes c
countInnerNodes (Leaf x) = 0

decodeInt :: BinTree (Int -> Bool) b -> Int -> b
decodeInt (Leaf b) p = b
decodeInt (Node x y z) p = if (x(p) == True) then decodeInt z p else decodeInt y p

decode :: BinTree (Int -> Bool) b -> [Int] -> String
decode x [] = "empty list"
decode x xs = ??????

在调用解码时,如何使用map获得这样的结果?

decode Tree [1,2,3,4] 
  = [decodeInt Tree (1), decodeInt Tree (2), 
     decodeInt Tree (3), decodeInt Tree (4)]

/ edit:跟进 假设我们要创建一个类似以下的函数

mapTree (\x -> ’e’) example

mapTree应该返回BinTree,就像示例一样,唯一的区别是每个Leaf的Char已被替换为'e'。我该怎么做?我昨天开始了Haskell,所以我对函数式编程很陌生。

1 个答案:

答案 0 :(得分:2)

decodeInt :: BinTree (Int -> Bool) b -> Int -> b,因此假设t :: BinTree (Int -> Bool) b,然后假设decodeInt t :: Int -> b。您将那个功能映射到Int个列表上。

decode t xs = let y = map (decodeInt t) xs
              in ...

您仍然需要弄清楚如何将y转换为String期望返回的decode值。

相关问题