简体   繁体   中英

When tracing in Haskell, how does one `show` a value whose data type is not known at compile-time?

I am using GHC version 8.0.2 on Windows 7, & module Debug.Trace . In the trace of the parse function below, my insertion of ++ show first results in the following error:

  • No instance for (Show a) arising from a use of `show' Possible fix: add (Show a) to the context of the type signature for: parse :: Parser a -> String -> [(a, String)]
  • In the first argument of (++)', namely show first' In the second argument of (++)', namely show first ++ "," ++ show second ++ ")]"' In the second argument of (++)', namely " -> [(" ++ show first ++ "," ++ show second ++ ")]"'

My question: is there a way to show the first element of the ordered pair (a,String) even though its type is not known at compile-time?

My source code is shown below:

{-# LANGUAGE MonomorphismRestriction #-}

import Data.Typeable
import Data.Char
import Debug.Trace

newtype Parser a = P ( String -> [(a,String)] )

parse :: Parser a -> String -> [(a,String)]
parse (P p) input | trace
  ( let result  = (p input)
        element = head result
        first   = fst element
        second  = snd element
    in  ("parse maps " ++ input ++ " -> [(" ++ show first ++ "," ++ show second ++ ")]")
  ) False = undefined
parse (P p) input = p input

nextChar :: Parser Char
nextChar = P ( \input -> case input of { [] -> [] ; (c:cs) -> [(c,cs)] } )

I am hoping to trace evaluation of parse nextChar "ABCD" .

Yes, sure, just follow the instructions in the error:

parse :: Show a => Parser a -> String -> [(a,String)]

Once you're done debugging, you can delete the call to trace and the Show constraint; then you'll be able to parse un- Show able things again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM