bind 和 map

bind 和 map_ (returns.pointfree)

  • bind

    • 作用:把入参类型改成 Container 类型
    • 参数:

      1. Containner[value] -> Contaner[value]
      2. Containner[value] -> value
    • 让入参可以接收 Containner[value] 类型

      • 即,把原始函数 fn(value) -> value 转换成 new_fn(Container[value])-> value
  • map

    • 作用: 把入参类型和出参类型都改成 Container 类型
    • 让入参和出参都使用 Container[value]

      • 即,把原始函数 fn(value) -> value 转换成 new_fn(Container[value])-> Container[value]

map_ 例子 :

1
2
3
4
5
from returns.pointfree import map_, bind
from returns.pipeline import flow, pipe

In [56]: flow(Some(12), map_(lambda x: x))
Out[56]: <Some: 12>
  • 注意:

    • 这里 map_(lambda x: x)

      • 接收的数据是 Some(12), 从 value –> Some(value)
      • 返回的数据是 <Some(12)>, 即 Some(12), 从 value –> Some(value)

bind 例子

1
2
3
4
5
6
7
8
from returns.pointfree import map_, bind
from returns.pipeline import flow, pipe

In [61]: flow(Some(12), bind(lambda x: x))
Out[61]: 12

In [62]: flow(Some(12), bind(lambda x: Some(x)))
Out[62]: <Some: 12>
  • 注意:

    • 这里 bind(lambda x: x)

      • 接收的数据是 Some(12)
      • 返回的数据是 12, 即原来 lambda 函数的返回类型 int
    • 这里 bind(lambda x: Some(x))

      • 接收的数据是 Some(12)
      • 返回的数据是 <Some(12)>, 即原来 lambda 函数的返回类型 Some(int)

contaner.bind 和 container.map