Fully Qualilfied Operator?


#1

I want to use a little of elm/parser. Can I reference Parser.(|.) without importing the operator at the top level? So far neither Parser.|. or Parser.(|.) works.

Currently, I could just import them, as long as I never need to import another operator by the same name.


#2

Since Elm 0.19 doesn’t allow user-defined operators, you’re very unlikely (maybe even guaranteed?) to never run into a conflict with another operator, since all the operators you could possibly use are defined in the elm/* packages.


#3

I might try something like this: first, create a Parser.NamedFunctions or similar module:

module Parser.NamedFunctions exposing (keep, ignore)

import Parser exposing (Parser, (|.), (|=))

keep : Parser keep -> Parser (keep -> a) -> Parser a
keep item parser =
    parser |= item

ignore : Parser ignore -> Parser a -> Parser a
ignore item parser =
    parser |. item

Then use it by ‘merging’ it with the actual Parser module:

module Main

import Parser exposing (Parser)
import Parser.NamedFunctions as Parser

type alias Point =
   { x : Int
   , y : Int
   }
   
pointParser : Parser Point
pointParser =
    Parser.succeed Point
        |> Parser.ignore (Parser.symbol "(")
        |> Parser.keep Parser.int
        |> Parser.ignore (Parser.symbol ",")
        |> Parser.keep Parser.int
        |> Parser.ignore (Parser.symbol ")")

This way the operators are only exposed at the top level within the Parser.NamedFunctions module.

(Note: I agree with @adeschamps that you shouldn’t actually have to worry about conflicts. I just prefer normal functions to operators anyways!)


#4

To answer your question; no, infix functions cannot be referenced qualified. They must be imported and used by name only.

See this ellie example: https://ellie-app.com/4m2ZYgthsSNa1

If you change Basics.+ to simply + it will compile.
It doesn’t compile because elm doesn’t recognize the valid, qualified function name when it is also a valid infix function.

2 things:

  • This should probably work and should probably be considered a bug.
  • If not, the error message should probably be better.

To address your concern, adeschamps is correct. Since infix function creation is allowed only in packages from elm/core and elm/experiments, there is a reasonable guarantee you’ll be free from conflict and if there is a conflict it would probably be considered a bug.


#5

Thanks. Wondered if I was missing something. I knew it wasn’t a big deal without user operators, and that a renamer-module would be a workaround in a pinch.


#6

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.