where绑定,let绑定和单个赋值运算符(&lt ;-)之间的区别 [英] Difference between where bindings, let bindings and the single assignment operator (<-)

查看:114
本文介绍了where绑定,let绑定和单个赋值运算符(&lt ;-)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这三种语法之间的区别:

I do not understand the difference between the three syntaxes:

  • where a = f (b)
  • do a <- f (b)
  • do let a = f (b)
  • where a = f (b)
  • do a <- f (b)
  • do let a = f (b)

尽管a <- f(b)与其他两个有所不同,但我确实有所了解,在大多数情况下,我尝试了所有三个都可以工作.我还在网上的某个地方读到,每个块都应该尝试与一个let绑定相处,以便变得惯用".但是我似乎从来没有管理过.

I do understand somehow though that a <- f(b) is different from the other two, in most cases where I tried all three worked. Also I read somewhere on the net that per block you should try to get along with one let binding only in order to be "idiomatic". But I never seem to manage.

我该如何决定使用什么?

How do I decide what to use?

推荐答案

let foo = bar in ...只是将foo定义为与bar...上下文中完全相同;您可以简单地使用文本替换将...中所有foo的用法替换为(bar),并获得完全相同的结果.

let foo = bar in ... simply defines foo to be the exact same thing as bar within the context of ...; you could simply use textual substitution to replace all uses of foo in ... with (bar) and get the exact same result.

where子句与let...in表达式相似,但是位于函数子句的末尾,而不是表达式.例如,

where clauses are similar to let...in expressions, but go at the end of a function clause, instead of being an expression. For instance,

foo x
    | p1 = ... y ...
    | p2 = ... y ...
  where
    y = ...

如果不将防护更改为if...then...else,则无法用let...in重写此内容.通常,纯粹出于样式原因,在let...in子句中使用where子句.

There is no way to rewrite this with let...in without changing the guards into if...then...elses. Often, where clauses are used over let...in clauses purely for reasons of style.

bind运算符完全不同.在do表示法中使用它从单子计算中提取"一个值.也就是说,如果foo具有类型m a,则在x <- foo之后,x具有类型a.所有其他绑定"形式都只定义名称,但是<-用于将计算结果从单子内部绑定. <-只能在do块内使用,因此它专门用于与绑定结果的动作在同一monad中构建更大的计算.

The bind operator is something different entirely. It's used in do notation to "extract" a value from a monadic computation. That is, if foo has the type m a, then after x <- foo, x has the type a. All the other "binding" forms just define names, but <- is used for binding a computation's result to a name from within a monad. <- can only be used inside a do block, so it's exclusively used to build up a larger computation in the same monad as the action you're binding the result of.

let foo = bar只是一种方便;您可以重写:

let foo = bar in do notation is just a convenience; you can rewrite:

do let foo = bar
   ...

let foo = bar
in do ...

但是当您有很多这样的绑定时,这会变得混乱,因为do块越来越嵌套.

but that gets messy when you have a lot of such bindings, as the do blocks get nested deeper and deeper.

我不知道您提到的建议是什么;您可以在let...in块中定义多个变量,并且

I don't know what the advice you mentioned is talking about; you can define multiple variables in a let...in block just fine, and

let foo = ...
    bar ...
in ...

let foo = ...
in let bar = ...
   in ...

这篇关于where绑定,let绑定和单个赋值运算符(&lt ;-)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆