使用函子<$>的困惑

时间:2018-11-06 04:41:53

标签: haskell functor

为什么行代码

public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsAdapter.GeneralViewHolder> {
    private final ArrayList<ArrayList<ExpenseData>> expenseData;
    private final Activity activity;
    private final double walletBalance;
    private final double totalExpenseAmount;

    public TransactionsAdapter(Activity activity, ArrayList<ArrayList<ExpenseData>> expenseData, double walletBalance, double totalExpenseAmount) {
        this.expenseData = expenseData;
        this.activity = activity;
        this.walletBalance = walletBalance;
        this.totalExpenseAmount = totalExpenseAmount;
    }

function remove(){ var task = this.event.currentTarget.parentNode; document.getElementById("myUl").removeChild(task); } 之后有一个额外的函子?根据我的理解,我知道LHS功能将在RHS上使用,但是由于有一个附加的函子,我不知道它是如何工作的。

generateScripts pb = (greet <$>) <$> (maybeName <$> pb
greet

3 个答案:

答案 0 :(得分:5)

pb(String, String)元组的列表。

maybeName <$> pbmaybeName映射到该列表,得到[Maybe String](Maybes列表)。有问题的函子是[]

(greet <$>) <$> ...(greet <$>)映射到该列表,即,它将(greet <$>)应用于列表的每个元素(类型为Maybe String的元素)。有问题的函子是[]

(greet <$>)greet上映射Maybe String。有问题的函子是Maybe

通常,如果您具有函数f :: a -> b,则可以使用(f <$>) :: (Functor f) => f a -> f b((f <$>) <$>) :: (Functor f, Functor g) => g (f a) -> g (f b)。每个<$>都映射到函子的另一层。

在这种情况下,我们有g = []f = Maybe,因此这有效地使greet :: String -> String在字符串嵌套两个级别的结构上运行,例如[Maybe String]。 / p>

答案 1 :(得分:3)

(greet <$>)是一个函数,适用于Maybe String类型的每个元素,而(greet <$>) <$>适用于整个列表,即[Maybe String],如图所示

(greet <$>) <$> (maybeName <$> pb)
= (greet <$>) <$> [Just "Bob", Nothing, Just "Alice"]
= [greet <$> Just "Bob", greet <$> Nothing, greet <$> Just "Alice"] 

答案 2 :(得分:0)

看起来<$>附近的greetfmap的{​​{1}},也就是说,如果值为Maybe,则将greet应用于x Just x,对于Nothing则不执行任何操作。

因此,maybeName <$> pbmaybeName函数映射到pb列表上,中间的<$>greet <$>映射到结果上,并将greet <$>本身会用Just修改greet的值。