Haskell code prints out a list for ints but not for chars - haskell

My code currently looks like this. It is supposed to show the possible first symbols in the regular expression definition given to us beforehand. I am supposed to print these out as a list. For example, if the answer is supposed to be [1,2], it will come out [1,2] but when the answer is supposed to be ['1','2'] it will come out "12" or when it is supposed to be ['a', 'b'] it will come out "ab". What am I doing wrong?
data RE a -- regular expressions over an alphabet defined by 'a'
= Empty -- empty regular expression
| Sym a -- match the given symbol
| RE a :+: RE a -- concatenation of two regular expressions
| RE a :|: RE a -- choice between two regular expressions
| Rep (RE a) -- zero or more repetitions of a regular expression
| Rep1 (RE a) -- one or more repetitions of a regular expression
deriving (Show)
firstMatches :: RE a -> [a]
firstMatches Empty = []
firstMatches (Sym a)= a:list
firstMatches(Rep(a))=firstMatches a
firstMatches(Rep1(a))=firstMatches a
firstMatches (Empty :+: b)= firstMatches b
firstMatches (a :+: _) = firstMatches a
firstMatches (a :|: b)= firstMatches a ++ firstMatches b

You're not doing anything wrong.
String is a type synonym for [Char], so if you try to print a [Char] it will print as a String. This is somewhat of a special case, and it can be a little weird.
Show is the typeclass used to print things as a string. The definition of Show is something like this:
class Show a where
showsPrec :: Int -> a -> ShowS
show :: a -> String
showList :: [a] -> ShowS
The showList function is optional. The documentation states:
The method showList is provided to allow the programmer to give a specialised way of showing lists of values. For example, this is used by the predefined Show instance of the Char type, where values of type String should be shown in double quotes, rather than between square brackets.
So if you define a new type and instantiate Show, you can optionally define a special way to show a list of your type, separate from the way it's normally shown and separate from the way lists are normally shown. Char takes advantage of this, in that a [Char] (or equivalently, a String), is shown with double-quotes instead of as a list of Char values.
I can't think of a way to get it to use the default show for a [Char]. I don't think there is one. A workaround might be to create a newtype wrapping Char with its own Show that uses the default showList implementation, but that doesn't seem appropriate here.
If this is homework, I'd expect the grader to know about this already, and I seriously doubt you'd get marked down for it, especially since the problem doesn't appear to be about show at all.

Related

XMonad: How to write functions involving the `Query` datatype?

Problem
I have a feeling that the reason for this question is going to ultimately come down to me just being new at/not understanding Haskell, so I'll try to be as detailed as I can with my description, to make it somewhat generic.
I am using a custom XMonad config as my window manager, defined in a file xmonad.hs.
The XMonad manageHook is what I use to handle when certain applications need to open in a certain type of window or on a certain workspace, etc.
https://hackage.haskell.org/package/xmonad-0.17.0/docs/XMonad-ManageHook.html
Currently, a bunch of lines in my manageHook in xmonad.hs look like this:
className =? "xxxx" --> doSomething
Here is my current understanding of the line above:
These expressions involve the value of className, defined in XMonad.Hooks.ManageHook, which is of the Query type (Query [Char], to be more specific).
https://hackage.haskell.org/package/xmonad-0.17.0/docs/XMonad-ManageHook.html
Query is defined in XMonad.Core. https://hackage.haskell.org/package/xmonad-0.17.0/docs/XMonad-Core.html#t:Query
=? takes the Query [Char] on the left and the [Char] literal on the right and returns a value of type Query Bool; the value will be True if the [Char]s are equal and False otherwise (I think?)
--> takes the Query Bool on the left and an action on the right and executes the action if the value of the Query Bool is True.
https://hackage.haskell.org/package/xmonad-0.17.0/docs/XMonad-ManageHook.html
However, this is only useful to me when I know the exact class name of an application I want to apply a rule to, which is not always the case. So, I took a look at xmonad-contrib to get some ideas as to what other functions I could define.
In XMonad.Hooks.ManageHelpers (https://hackage.haskell.org/package/xmonad-contrib-0.17.0/docs/XMonad-Hooks-ManageHelpers.html), there is ^?, which would be used like below:
className ^? "xxxx" --> doSomething
From my understanding, ^? takes the Query [Char] on the left and the [Char] literal on the right and returns a value type of Query Bool; the value will be True if the [Char] on the left isPrefixOf the [Char] on the right and False otherwise (I think?)
What I would like to create is a new function that is similar, but reversed. Something like,
"xxxx" ?^ className --> doSomething
where ?^ takes the [Char] literal on the left and the Query [Char] on the right and returns a value of type Query Bool; the value should be True if the [Char] on the left isPrefixOf the [Char] on the right and False otherwise.
(In other words, I want to define a new function that checks if some string literal is a prefix of the class name, rather than checking if the class name is a prefix of some string literal.)
Initially, I thought this should be easy, but looking at the source code for ^?, I realized there must be something I am fundamentally missing about my understanding of Haskell.
Here is the definition of ^?:
(^?) :: (Eq a, Functor m) => m [a] -> [a] -> m Bool
q ^? x = fmap (`isPrefixOf` x) q
https://hackage.haskell.org/package/xmonad-contrib-0.17.0/docs/src/XMonad.Hooks.ManageHelpers.html#%5E%3F
What I do not understand is how I would write a function that is a reversed version of this. This definitely won't work:
(?^) :: (Eq a, Functor m) => [a] -> m [a] -> m Bool
x ?^ q = fmap (`isPrefixOf` q) q
yet I do not understand why. What property does Query have that (Query [a]) isPrefixOf ([a]) is acceptable, but not ([a]) isPrefixOf (Query [a])?
Furthermore, how can I go about defining a function with the desired behavior? I am still pretty new to Haskell, so I do not know where to start.
Solution
I was closer than I thought. See the answer for more details, but the solution was just to fix my syntax for the invocation of isPrefixOf (oops):
x ?^ q = fmap (x `isPrefixOf`) q
You gotta switch the arguments to isPrefixOf!
x ?^ q = fmap (x `isPrefixOf`) q
Other spellings are possible, such as this version that doesn't use the infix form of isPrefixOf:
x ^? q = isPrefixOf x <$> q
((<$>) is another name for fmap.)

Haskell list type conversion

Support I have a list of type [Char], and the values enclosed are values of a different type if I remove their quotations which describe them as characters. e.g. ['2','3','4'] represents a list of integers given we change their type.
I have a similar but more complicated requirement, I need to change a [Char] to [SomeType] where SomeType is some arbitrary type corresponding to the values without the character quotations.
Assuming you have some function foo :: Char -> SomeType, you just need to map this function over your list of Char.
bar :: [Char] -> [SomeType]
bar cs = map foo cs
I hope I get this correctly and there is a way (if the data-constructors are just one-letters too) - you use the auto-deriving for Read:
data X = A | B | Y
deriving (Show, Read)
parse :: String -> [X]
parse = map (read . return)
(the return will just wrap a single character back into a singleton-list making it a String)
example
λ> parse "BAY"
[B,A,Y]

to overload a data type or to use a similar one?

This is more of a question about a programming style and common practices. But I feel that it does not fit into the code review forum...
My program parses regular expressions and processes them. A regular expression can have the usual elements (Kleene closure, concatenation, etc) and it also can have references to other regular expressions by their names, like macros:
data Regex a = Epsilon
| Literal a
| Ranges [(a, a)]
| Ref String
| Then (Regex a) (Regex a)
| Or (Regex a) (Regex a)
| Star (Regex a)
After I process a regular expression and resolve all macro references, and convert Literal elements to Range elements (this is needed for my purposes), I end up with a type that cannot and must not have Ref and Literal, so in my functions that work with it I do something like:
foo (Literal _) = error "unexpected literal"
foo (Ref _) = error "unexpected reference"
foo (Epsilon) = ...
foo (Star x) = ...
...
This looks ugly to me because it does runtime checks instead of checks during compilation. Not a very haskell kind of approach.
So maybe I can introduce another data type which is very similar to the original one and use that?
data RegexSimple a = Epsilon2
| Ranges2 [(a, a)]
| Then2 (Regex a) (Regex a)
| Or2 (Regex a) (Regex a)
| Star2 (Regex a)
That would work, but here I have a lot of duplication and also the nice and descriptive names of constructors are taken now and I need to invent new ones...
What would the experts do here? I want to learn : )
I don't know what the rest of your code looks like, so this solution may require you to rethink certain aspects, but the most "haskell-ish" solution to this problem would probably be to use GADTs and phantom types. Together, they basically allow you to create arbitrary subtypes for more flexible type safety. You would redefine your types like so.
{-# LANGUAGE GADTs #-}
data Literal
data Ref
data Rangeable
data Regex t a where
Epsilon :: Regex Rangeable a
Literal :: a -> Regex Literal a
Ranges :: [(a, a)] -> Regex Rangeable a
Ref :: String -> Regex Ref a
Then :: Regex t' a -> Regex t' a -> Regex Rangeable a
Or :: Regex t' a -> Regex t' a -> Regex Rangeable a
Star :: Regex t' a -> Regex Rangeable
Then you can define
foo :: Regex Rangeable a
foo (Epsilon) = ...
foo s#(Star a) = ...
Now, statements like foo $ Literal 'c' will fail compile-time type-checks.
I'm not an expert but it's a problem I have also myself (even though it more with product type than sum type).
The obvious solution is to reuse RegexSimple in Regex so that
data Regex a = Ref a | Literal a | SimpleR (SimpleRegex a)
another way is to parametrize Regex with a functor
data Regex f a = Literal (f a) | Ref (f a) | Epsilon a ...
and use either Regex Id or Regex Void.
Another way is just to use Maybe
data Regex a = Literal (Maybe a) | Epsilon a ...
But this it less clean because you can't enforce a function to only accept simple regex.

Why can't I use the type `Show a => [Something -> a]`?

I have a record type say
data Rec {
recNumber :: Int
, recName :: String
-- more fields of various types
}
And I want to write a toString function for Rec :
recToString :: Rec -> String
recToString r = intercalate "\t" $ map ($ r) fields
where fields = [show . recNumber, show . recName]
This works. fields has type [Rec -> String]. But I'm lazy and I would prefer writing
recToString r = intercalate "\t" $ map (\f -> show $ f r) fields
where fields = [recNumber, recName]
But this doesn't work. Intuitively I would say fields has type Show a => [Rec -> a] and this should be ok. But Haskell doesn't allow it.
I'd like to understand what is going on here. Would I be right if I said that in the first case I get a list of functions such that the 2 instances of show are actually not the same function, but Haskell is able to determine which is which at compile time (which is why it's ok).
[show . recNumber, show . recName]
^-- This is show in instance Show Number
^-- This is show in instance Show String
Whereas in the second case, I only have one literal use of show in the code, and that would have to refer to multiple instances, not determined at compile time ?
map (\f -> show $ f r) fields
^-- Must be both instances at the same time
Can someone help me understand this ? And also are there workarounds or type system expansions that allow this ?
The type signature doesn't say what you think it says.
This seems to be a common misunderstanding. Consider the function
foo :: Show a => Rec -> a
People frequently seem to think this means that "foo can return any type that it wants to, so long as that type supports Show". It doesn't.
What it actually means is that foo must be able to return any possible type, because the caller gets to choose what the return type should be.
A few moments' thought will reveal that foo actually cannot exist. There is no way to turn a Rec into any possible type that can ever exist. It can't be done.
People often try to do something like Show a => [a] to mean "a list of mixed types but they all have Show". That obviously doesn't work; this type actually means that the list elements can be any type, but they still have to be all the same.
What you're trying to do seems reasonable enough. Unfortunately, I think your first example is about as close as you can get. You could try using tuples and lenses to get around this. You could try using Template Haskell instead. But unless you've got a hell of a lot of fields, it's probably not even worth the effort.
The type you actually want is not:
Show a => [Rec -> a]
Any type declaration with unbound type variables has an implicit forall. The above is equivalent to:
forall a. Show a => [Rec -> a]
This isn't what you wan't, because the a must be specialized to a single type for the entire list. (By the caller, to any one type they choose, as MathematicalOrchid points out.) Because you want the a of each element in the list to be able to be instantiated differently... what you are actually seeking is an existential type.
[exists a. Show a => Rec -> a]
You are wishing for a form of subtyping that Haskell does not support very well. The above syntax is not supported at all by GHC. You can use newtypes to sort of accomplish this:
{-# LANGUAGE ExistentialQuantification #-}
newtype Showy = forall a. Show a => Showy a
fields :: [Rec -> Showy]
fields = [Showy . recNumber, Showy . recName]
But unfortunatley, that is just as tedious as converting directly to strings, isn't it?
I don't believe that lens is capable of getting around this particular weakness of the Haskell type system:
recToString :: Rec -> String
recToString r = intercalate "\t" $ toListOf (each . to fieldShown) fields
where fields = (recNumber, recName)
fieldShown f = show (f r)
-- error: Couldn't match type Int with [Char]
Suppose the fields do have the same type:
fields = [recNumber, recNumber]
Then it works, and Haskell figures out which show function instance to use at compile time; it doesn't have to look it up dynamically.
If you manually write out show each time, as in your original example, then Haskell can determine the correct instance for each call to show at compile time.
As for existentials... it depends on implementation, but presumably, the compiler cannot determine which instance to use statically, so a dynamic lookup will be used instead.
I'd like to suggest something very simple instead:
recToString r = intercalate "\t" [s recNumber, s recName]
where s f = show (f r)
All the elements of a list in Haskell must have the same type, so a list containing one Int and one String simply cannot exist. It is possible to get around this in GHC using existential types, but you probably shouldn't (this use of existentials is widely considered an anti-pattern, and it doesn't tend to perform terribly well). Another option would be to switch from a list to a tuple, and use some weird stuff from the lens package to map over both parts. It might even work.

printing a list of type signatures

I want to be able to type the following in ghci:
map showTypeSignature [(+),(-),show]
I want ghci to return the following list of Strings:
["(+) :: Num a => a -> a -> a","(-) :: Num a => a -> a -> a","show :: Show a => a -> String"]
Naturally, the first place that I run into trouble is that I cannot construct the first list, as the type signatures of the functions don't match. What can I do to construct such a list? How does ghci accomplish the printing of type signatures? Where is the ghci command :t defined (its source)?
What you're asking for isn't really possible. You cannot easily determine the type signature of a Haskell term from within Haskell. At run-time, there's hardly any type information available. The GHCi command :t is a GHCi command, not an interpreted Haskell function, for a reason.
To do something that comes close to what you want you'll have to use GHC itself, as a library. GHC offers the GHC API for such purposes. But then you'll not be able to use arbitrary Haskell terms, but will have to start with a String representation of your terms. Also, invoking the compiler at run-time will necessarily produce an IO output.
kosmikus is right, this doesn't really work out. And shouldn't, the static type system is one of Haskell's most distinguishing features!
However, you can emulate this for monomorphic functions quite well using the Dynamic existential:
showTypeSignature :: Dynamic -> String
showTypeSignature = show . dynTypeRep
Prelude Data.Dynamic> map showTypeSignature [toDyn (+), toDyn (-), toDyn (show)]
["Integer -> Integer -> Integer","Integer -> Integer -> Integer","() -> [Char]"]
As you see ghci had to boil the functions down to monomorphic type here for this to work, which particularly for show is patently useless.
The answers you have about why you can't do this are very good, but there may be another option. If you don't care about getting a Haskell list, and just want to see the types of a bunch of things, you can define a custom GHCi command, say :ts, that shows you the types of a list of things; to wit,
Prelude> :ts (+) (-) show
(+) :: Num a => a -> a -> a
(-) :: Num a => a -> a -> a
show :: Show a => a -> String
To do this, we use :def; :def NAME EXPR, where NAME is an identifier and EXPR is a Haskell expression of type String -> IO String, defines the GHCi command :NAME. Running :NAME ARGS evaluates EXPR ARGS to produce a string, and then runs the resulting string in GHCi. This is less confusing than it sounds. Here's what we do:
Prelude> :def ts return . unlines . map (":type " ++) . words
Prelude> :ts (+) (-) show
(+) :: Num a => a -> a -> a
(-) :: Num a => a -> a -> a
show :: Show a => a -> String
What's going on? This defines :ts to evaluate return . unlines . map (":t " ++) . words, which does the following:
words: Takes a string and splits it on whitespace; e.g., "(+) (-) show" becomes ["(+)", "(-)", "show"].
map (":type " ++): Takes each of the words from before and prepends ":type "; e.g., ["(+)", "(-)", "show"] becomes [":type (+)", ":type (-)", ":type show"]. Notice that we now have a list of GHCi commands.
unlines: Takes a list of strings and puts newlines after each one; e.g., [":type (+)", ":type (-)", ":type show"] becomes ":type (+)\n:type (-)\n:type show\n". Notice that if we pasted this string into GHCi, it would produce the type signatures we want.
return: Lifts a String to an IO String, because that's the type we need.
Thus, :ts name₁ name₂ ... nameₙ will evaluate :type name₁, :type name₂, …, :type nameₙ in succession and prints out the results. Again, you can't get a real list this way, but if you just want to see the types, this will work.

Resources