haskell - Haskell 使用 map 调用具有多个参数的函数
问题描述
假设我们有以下代码表示二叉树,其中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 = ??????
调用解码时如何使用地图获得这样的结果?
decode Tree [1,2,3,4]
= [decodeInt Tree (1), decodeInt Tree (2),
decodeInt Tree (3), decodeInt Tree (4)]
/edit: Followup 假设我们想创建一个函数,如下所示
mapTree (\x -> ’e’) example
mapTree 应该像示例一样返回 BinTree,唯一的区别是每个 Leaf 的 Char 已被替换为“e”。我该如何做到这一点?我昨天开始使用 Haskell,所以我对函数式编程很陌生。
解决方案
decodeInt :: BinTree (Int -> Bool) b -> Int -> b
, 所以假设t :: BinTree (Int -> Bool) b
, 那么decodeInt t :: Int -> b
. 您将该函数映射到您的Int
s 列表上。
decode t xs = let y = map (decodeInt t) xs
in ...
您仍然需要弄清楚如何转换为预期返回y
的String
值。decode
推荐阅读
- c++ - 检查 gdb 中的静态 const 类成员
- javascript - 使用新值重新执行 await/async/promise.all 函数
- python - ModuleNotFoundError:没有名为“global_state”的模块
- django - Django - 测试功能视图的 URL 时是否需要所有相关模型?
- java - 尝试安装 java2python 并不断收到以下错误消息:
- haxm - 英特尔 x86 仿真器加速器(HAXM 安装程序)无法安装:java.nio.file.FileSystemException: F:\sdk\.temp: 设备未准备好
- android - 外部驱动器上的 React-Native 应用程序仅适用于防火墙关闭
- html - webkit-line-clamp 不适用于按钮
- python - 您如何使用 Etsy updateinventory() API 添加大量变体而不使 URL 过长?
- at-sign - AtKeys 元数据中的刷新时间 (TTR)、生存时间 (TTL) 和出生时间 (TTB)、级联删除 (CCD) 有什么用?