Pattern match on Data.Text constant?

I guess I am blind or something, so that I could not find the idiomatic way to pattern match on Data.Text constants.

Basically, what I want to do is the following:

getTempDriverName dir >>= \case
  "k10temp" -> handleK10Temp dir
  "coretemp.0" -> handleCoreTemp dir
  _ -> fail "Wrong driver"

I want to use Data.Text, since String is lazy and no one knows when the file would be closed. However, apparently the following does not work:

getTempDriverName dir >>= \case
  T.pack "k10temp" -> handleK10Temp dir
  T.pack "coretemp.0" -> handleCoreTemp dir
  _ -> fail "Wrong driver"

Any ideas? What would be the idiomatic way? Of course I could do this:

getTempDriverName dir >>= \case
  name
    | name == T.pack "k10temp" -> handleK10Temp dir
    | name == T.pack "coretemp.0" -> handleCoreTemp dir
    | otherwise -> fail "Wrong driver"

but it involves binding a name I do not care for.

>Solution :

If you really want to pattern match here, you can use the OverloadedStrings extension because Text is an instance of IsString. With this extension, strings have type IsString a => a, just like numbers have type Num a => a:

λ> :set -XOverloadedStrings
λ> :t "hello"
"hello" :: IsString a => a
λ> "sample" :: Text
"sample"

In code:

-- put this pragma at the top of the file
{-# LANGUAGE OverloadedStrings #-}

getTempDriverName dir >>= \case
  "k10temp" -> handleK10Temp dir
  "coretemp.0" -> handleCoreTemp dir
  _ -> fail "Wrong driver"

Leave a Reply