Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading