Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot find pattern" when using a tagged union type

Tags:

elm

I have an app that spans multiple modules. In the first, I model my problem, creating several data types. In the second, I'm putting views.

One of those types is a tagged union type:

type alias Letter = Char
type GuessedLetter = Guessed Letter | Unguessed

In my View module, I have a function for displaying a letter:

guessToChar : GuessedLetter -> Char
guessToChar guess =
  case guess of
    Guessed l -> l
    Unguessed -> '_'

But when I try compiling these files, I get the following error:

## ERRORS in src/Views.elm #####################################################

-- NAMING ERROR -------------------------------------------------- src/Views.elm

Cannot find pattern `Guessed`

21|       Guessed l -> l
          ^^^^^^^^^

-- NAMING ERROR -------------------------------------------------- src/Views.elm

Cannot find pattern `Unguessed`

22|       Unguessed -> '_'
          ^^^^^^^^^

Detected errors in 1 module.

I thought "Maybe I should export the tags as well as the type?", but neither adding the tags to the module exports nor attempting to fully-qualify the tags (GuessedLetter.Guessed) has resolved the issue.

How do I fix this function?

like image 310
andrewdotnich Avatar asked Jul 23 '15 01:07

andrewdotnich


1 Answers

As I suspected, if you want to use the tags outside the module, you have to export them too. (I just wan't sure how).

To do that, add the tags in a comma-separated list inside parentheses.

From the source code for Maybe (a type that 'worked' the way I wanted mine to):

module Maybe exposing
  ( Maybe(Just,Nothing)
  , andThen
  , map, map2, map3, map4, map5
  , withDefault
  , oneOf
  )

Or in my case:

module Game exposing (Letter, GuessedLetter(Guessed, Unguessed))

On the importing side, you can then choose to fully-qualify the tags (with the module, not the type):

import Game exposing GuessedLetter
{- ... -}

guessToChar : GuessedLetter -> Char
guessToChar guess =
  case guess of
    Game.Guessed l -> l
    Game.Unguessed -> '_'

or expose the tags too:

import Game exposing GuessedLetter(Guessed, Unguessed)
{- ... -}

guessToChar : GuessedLetter -> Char
guessToChar guess =
  case guess of
    Guessed l -> l
    Unguessed -> '_'
like image 146
andrewdotnich Avatar answered Oct 09 '22 02:10

andrewdotnich