Why Haskell range needs spaces when using [LT .. GT]?

前端 未结 3 1229
猫巷女王i
猫巷女王i 2021-01-07 22:01

Why is it that when I do range in Haskell, this works:

[LT .. GT]

but this doesn\'t:

[LT..GT]

and what do

相关标签:
3条回答
  • 2021-01-07 22:20

    It's because LT.. is interpreted as the . operator in the LT module.


    <interactive>:1:2:
        Failed to load interface for `LT':
          Use -v to see a list of the files searched for.
    

    It means GHC cannot find a module named LT. The same message appears if you use a qualified name with a non-existing library:

    Prelude> SDJKASD.sdfhj
    
    <interactive>:1:1:
        Failed to load interface for `SDJKASD':
          Use -v to see a list of the files searched for.
    

    <interactive>:1:2:
        A section must be enclosed in parentheses thus: (`LT..` GT)
    

    In Haskell, a section is an infix operator with a partial application, e.g. (* 3), which is equivalent to \x -> x * 3.

    In your case, LT.. is interpreted as an infix . operator, and the GT is part of the section formed with this operator.

    A section must be enclosed in parenthesis, and since the misinterpretation does not, the parser will complain like this.

    Another example of the error:

    Prelude> [* 3]
    
    <interactive>:1:2:
        A section must be enclosed in parentheses thus: (* 3)
    
    0 讨论(0)
  • 2021-01-07 22:30

    Because of the maximal munch rule, LT.. gets interpreted as the qualified name of the (.) operator in the LT module. Since you can define your own operators in Haskell, the language allows you to fully qualify the names of operators in the same way as you can with functions.

    This leads to an ambiguity with the .. used in ranges when the name of the operator starts with ., which is resolved by using the maximal munch rule, which says that the longest match wins.

    For example, Prelude.. is the qualified name of the function composition operator.

    > :info Prelude..
    (.) :: (b -> c) -> (a -> b) -> a -> c   -- Defined in GHC.Base
    infixr 9 .
    > (+3) Prelude.. (*2) $ 42
    87
    

    The reason why [1..3] or [x..y] works, is because a module name must begin with an upper case letter, so 1.. and x.. cannot be qualified names.

    0 讨论(0)
  • 2021-01-07 22:38

    Failed to load interface for `LT':

    Kenny and Hammar have explained what this means: LT.. is assumed to be the . function in the LT module. Since there is no LT module, your interpreter naturally cannot load it.

    A section must be enclosed in parentheses thus: (LT.. GT)

    Along the same vein, assuming that LT.. is a reference to the . function in the LT module, your interpreter is apparently assuming that you made the mistake of using square brackets instead of parens in order to for a "section" ( a section is, for example, (+1) ).

    This is simply an obnoxious little wart in the Haskell language; just remember to use spaces.

    0 讨论(0)
提交回复
热议问题