Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

Haskell - Pattern Synonyms, View Patterns, GADTs

I'm now trying out 2 pieces of code from:

https://mpickering.github.io/posts/2015-12-12-pattern-synonyms-8.html

{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE GADTs #-}

In the first piece of code:

pattern IsTrue :: Show a => a
pattern IsTrue <- ((== "True") . show -> True)
test10 = IsTrue "True"

The following error was thrown:

? non-bidirectional pattern synonym ‘IsTrue’ used in an expression
? In the expression: IsTrue "True"

In the second piece of code:

data T where
  MkT :: (Show b) => b -> T
pattern ExNumPat :: () => Show b => b -> T
pattern ExNumPat x = MkT x
test11 = ExNumPat True

The following error was thrown when I run test11:

? No instance for (Show T) arising from a use of ‘print’

What caused these 2 errors and how do I resolve them? And how do the patterns work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First error

Problem 1: Since your pattern synonym uses <- and not =, and it doesn't have a where, it's unidirectional, so you can only match on it, not use it as a value. You can make it explicitly bidirectional by doing something like this:

pattern IsTrue :: (Read a, Show a) => a
pattern IsTrue <- ((== "True") . show -> True)
  where IsTrue = read "True"

Although for that particular pattern, that's really contrived and probably never actually useful.

Problem 2: Functions don't have Show instances, and in IsTrue "True", you're trying to use IsTrue as a function even though it requires a Show instance.

Second error

Your code only ensures that the b in MkT has a Show instance, but you're trying to show the whole T, which does not have a Show instance. Either pattern-match the b back out of it and just show that, or add a Show instance to t.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...