为什么我不应该混合使用制表符和空格? [英] Why shouldn't I mix tabs and spaces?

查看:17
本文介绍了为什么我不应该混合使用制表符和空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常读到我不应该在 Haskell 中混合使用制表符和空格,或者根本不应该使用制表符.为什么?

I often read that I shouldn't mix tabs and spaces in Haskell, or that I shouldn't use tabs at all. Why?

推荐答案

问题是双重的.首先,Haskell 对缩进敏感,例如以下代码无效:

The problem is twofold. First of all, Haskell is indentation sensitive, e.g. the following code isn't valid:

example = (a, b)
  where
    a = "Hello"
     b = "World"

两个绑定都需要缩进相同数量的空格/制表符(请参阅越位规则).虽然在这种情况下很明显,但它在下面的情况中相当隐藏,我用 · 表示一个空格,用 » 表示一个制表符:

Both bindings need to be indented with the same number of spaces/tabs (see off-side rule). While it's obvious in this case, it's rather hidden in the following one, where I denote a space by · and a tab by »:

example = (a, b)
··where
····a = "Hello"
»   b = "World"

如果编辑器将显示与 4 的倍数对齐的选项卡,这将看起来像有效的 Haskell 代码.但事实并非如此.Haskell 选项卡按 8 的倍数对齐,因此代码将被解释为:

This will look like valid Haskell code if the editor will show tabs aligned to multiples by four. But it isn't. Haskell tabs are aligned by multiples of eight, so the code will be interpreted like this:

example = (a, b)
··where
····a = "Hello"
»       b = "World"

其次,如果您只使用选项卡,您可能会得到一个看起来不正确的布局.例如,如果选项卡显示有六个或更多空格(在本例中为八个),则以下代码看起来是正确的:

Second, if you use only tabs, you can end up with a layout that doesn't look right. For example, the following code looks correct if a tab gets displayed with six or more spaces (eight in this case):

example = (a, b)
»       where»  a = "Hello"
»       »       b = "World"

但在另一个使用 4 个空格的编辑器中,它看起来不再正确:

But in another editor that uses 4 spaces it won't look right anymore:

example = (a, b)
»   where»  a = "Hello"
»   »   b = "World"

不过,这仍然是正确的.但是,习惯使用空格的人可能会重新将 b' 绑定与空格并最终导致解析器错误.

It's still correct, though. However, someone who's used to spaces might reindent b' binding with spaces and end up with a parser error.

如果您在整个代码中强制执行代码约定,以确保仅在行首使用制表符并在 wherelet 之后使用换行符code>do 你可以避免一些问题(见11).但是,GHC 的当前版本默认会警告标签a>,因为他们 去过 a 来源 过去有很多解析器错误,所以你可能也想摆脱它们.

If you enforce a code convention throughout your code that makes sure that you only use tabs at the beginning of a line and use a newline after where, let or do you can avoid some of the problems (see 11). However, current releases of GHC warn about tabs by default, because they have been a source of many parser errors in the past, so you probably want to get rid of them too.

  • A reddit thread on the topic (majority pro spaces, but some pro tabs)
  • Good Haskell Style (pro spaces)
  • Yet Another Tabs v Space debate (pro mixing)

这篇关于为什么我不应该混合使用制表符和空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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