I need to create a function f:: Log->[String] that does that (((o, i ,d),s) = [(o, i ,d)]
type Log = (Plate, [String])
type Plate = (Pin, Pin, Pin)
type Pin = (Char, Int)
If you're on a page like this, click "Source" on the fir right side, next to the function that you're interested in.
If you need to look up a function, Hayoo! and Hoogle will link you to documentation pages like the one above.
An important thing to note, though is that show doesn't have one definition. show is a function defined for all data types in the Show (with a capital "S") typeclass. So for example, here is the full source for the Show typeclass. Show is defined within the typeclass as just show :: a -> String. But if you search for "instance Show Bool" or "instance Show Int", you'll find specific definitions.
For the second part of your question, the easiest way to get a show function for a new type is to simply write deriving (Show) below it. For example,
data Foo = Foo Int Int
deriving (Show)
Now I can use show on data with type Foo.
g :: Log -> [String]
g (plate, _) = [show plate]
Use hoogle to find this sort of information.
Example: http://www.haskell.org/hoogle/?hoogle=show
Once you've found the function you'd like in the list, click and there you'll find a Source link on the right hand side of the page.
NB this is an answer to the original question:
Where can I see the codes of the predefined functions in haskell ?? Mainly the function SHOW?
It's true that you can use Hoogle to search for functions defined in the Prelude (and other modules), but the source code itself is located at Hackage.
Hackage is a database of Haskell packages. You can download new packages from it, and also view the Haddock documentation for every package in the database.
This is the Haddock page for the standard Prelude. It documents the type classes, data types, types, and top-level functions exported by the Prelude module. To the right of each definition header is a link that says "Source". You can click this to be taken to an online copy of the source code for the module you're viewing.
On preview, you're now asking a different question entirely, and on preview again in fact the original question has been edited out of this post.
Your new question is unclear, but this solution will work to produce the output in your example.
> [fst ((('O',0),('I',0),('D',1)),"O->D")]
[(('O',0),('I',0),('D',1))]
I think you're using list notation instead of double quotes to identify Strings, by the way, so I fixed that around 0->D above. So you might also try this instead.
> show (fst ((('O',0),('I',0),('D',1)),"O->D"))
"(('O',0),('I',0),('D',1))"
This works because you have only defined type synonyms (by using type in your declarations instead of data) on data structures which already have Show instances.
Related
today on "adventures in functional programming with lenses" our hero attempts to define a prism over a list element that may or may not exist.
It's a bit tricky to explain, so to avoid the X, Y problem I'll give the actual use-case in all its glory.
I'm writing a Text editor in Haskell called Rasa, the whole idea is that it's extremely extensible, and that means most functionality is written as extensions. Since it's a core principle, extensions ALSO depend on other extensions, so I needed a way to store their state centrally such that all extensions depending on an extension could access its current 'extension state'. Of course the types of these states is not known to the core of the editor, so at the moment I'm storing a list of Dynamic values. When the extension stores the state it converts to a Dynamic, then it can be extracted later via a prism like so:
data Store = Store
{ _event :: [Event]
, _editor :: E.Editor
, _extState :: [Dynamic]
}
ext :: Typeable a => Traversal' Store a
ext = extState.traverse._Dynamic
So now ext is a polymorphic Traversal that essentially operates over only the Dynamics that 'match' the type in question (if you set to it it'll replace values of the same type, if you 'get' from it, it acts as a traversal over the Dynamics that match the type of the outbound value). If that seems like magic, it basically is...
BTW, I'd love to have exactly 1 copy of a given Extension's state object in the list at any time.
So getting and setting is actually working fine IFF there's already a value of the proper type in the list, my question is how can I make a version of this Traversal such that if a value of the proper type is in the list that it will replace it (and getting works as expected), but that will ADD a value to the list if the traversal is SET to and there's NO matching element in the list. I understand that Traversal's aren't supposed to change the number of elements that they're traversing, so perhaps this needs to be a prism or lens over the list itself?
I understand this is really confusing, so please ask clarifying questions :)
As for things I've taken a look at already, I was looking at prefixed and _Cons as possible ways to do this, but I'm just not quite sure how to wire it up. Maybe I'm barking up the wrong tree entirely.
I could perhaps add a default value to the end of the traversal somehow, but I don't want to require Monoid or Default so I can't conjure up elements from nowhere (and I only want to do it when SETTING).
I'm also open to discussions about whether this is actually the proper way to store this state at all, but it's the most elegant of solutions I've found so far (though I know typecasting at run time is sub-optimal). I've looked into the Vault type, but passing keys around didn't really work well when I tried it (and I imagine it has similar type-casting performance issues).
Cheers! Thanks for reading.
I think the list of extensions is not proper solution for you. I would be added something like _extState :: Map TypeRep Ext where data Ext = forall a. Ext a. Then I would be added the lens:
ext :: forall a . Typeable a => Lens' Store (Maybe a)
ext = _extState . at (typeRep (Proxy :: Proxy a)) . mapping coerce
where
coerce = iso (\(Ext x) -> unsafeCoerce x) Ext
This lens does like at. So you can simply get/set your extensions.
But there is one limitation, all extensions must be of different types.
Looking at the following code:
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
which is from the book Learn you a Haskell for Great Good, which accompanies this code example with the following text:
Notice that when defining a point, we used the same name for the data type and the value constructor. This has no special meaning, although it's common to use the same name as the type if there's only one value constructor.
Now my assumption is that data Point = ... is the data type, and ... = Point Float... is the value constructor.
My question is: Is it common to use the same name for the data type and value constructor in Haskell?
From my limited experience: Yes. It makes sense, too. Why would you call Point differently here? It perfectly describes the data type and is also clear to use for pattern matching like this
myFunc :: Point -> Bool
myFunc (Point 0 0) = True
myFunc _ = False
It is unambiguous since you can only put the data type in the type signature of the function.
This is not a direct answer, but a tip for people with the same question.
Syntax highlighting may help with the distinction between the two. For example a screenshot of some of the code mentioned before, from Visual Studio Code with a Haskell Syntax Highlighting extension (with customized color coding):
Not everybody seems to agree with the accepted answer, by the way. See for example this short post, as well as this r/haskell discussion about it.
I have many files that must be processed automatically. Each file holds the response of one student to an exercise which asks the student to give definitions for some functions given a type for each function.
My idea is to have an Haskell script that loads each student file, and verifies if each function has the expected type.
A constraint is that the student files are not defined as modules.
How can I do this?
My best alternative so far is to spawn a GHCi process that will read stdin from a "test file" with GHCi commands, for example:
:load student1.hs
:t g
... and so on ...
then parse the returned output from GHCi to find the types of the functions in the student file.
Is there another clean way to load an arbitrary Haskell file and introspect its code?
Thanks
Haskell does not save type information at runtime. In Haskell, types are used for pre-runtime type checking at the static analysis phase and are later erased. You can read more about Haskell's type system here.
Is there a reason you want to know the type of a function at runtime? maybe we can help with the problem itself :)
Edit based on your 2nd edit:
I don't have a good solution for you, but here is one idea that might work:
Run a script that for each student module will:
Take the name of the module and produce a file Test.hs:
module Test where
import [module-name]
test :: a -> b -> [(b,a)]
test = g
run ghc -fno-code Test.hs
check the output does not contain type errors
write results into a log file
I think if you have a dynamically determined number of .hs files, which you need to load, parse and introspect, you could/should use the GHC API instead.
See for example:
Using GHC API to compile Haskell sources to CORE and CORE to binary
https://mail.haskell.org/pipermail/haskell-cafe/2009-April/060705.html
These might not be something you can use directly — and I haven't done anything like this myself so far either — but these should get you started.
See also:
https://wiki.haskell.org/GHC/As_a_library
https://hackage.haskell.org/package/hint
The closest Haskell feature to that is Data.Typeable.typeOf. Here's a GHCi session:
> import Data.Typeable
> typeOf (undefined :: Int -> Char)
Int -> Char
> typeOf (undefined :: Int -> [Char])
Int -> [Char]
> typeOf (undefined :: Int -> Maybe [Char])
Int -> Maybe [Char]
> :t typeOf
typeOf :: Typeable a => a -> TypeRep
Under the hood, the Typeable a constraint forces Haskell to retain some type tags until runtime, so that they can be retrieved by typeOf. Normally, no such tags exist at runtime. The TypeRep type above is the type for such tags.
That being said, having such information is almost never needed in Haskell. If you are using typeOf to implement something, you are likely doing it wrong.
If you are using that to defer type checks to run time, when they could have been performed at compile time, e.g. using a Dynamic-like type for everything, then you are definitely doing it wrong.
If the function is supposed to be exported with a specific name, I think probably the easiest way would be to just write a test script that calls the functions and checks they return the right results. If the test script doesn't compile, the student's submission is incorrect.
The alternative is to use either the GHC API (kinda hard), or play with Template Haskell (simpler, but still not that simple).
Yet another possibility is to load the student's code into GHCi and use the :browse command to dump out everything that's exported. You can then grep for the term you're interested in. That should be quite easy to automate.
There's a catch, however: foo :: x -> x and foo :: a -> a are the same type, even though textually they don't match at all. You might contemplate trying to normalise the variable names, but it's worse: foo :: Int -> Int and foo :: Num x => x -> x don't look remotely the same, yet one type is an instance of the other.
...which I guess means I'm saying that my answer is bad? :-(
I'm using Haskell 2010.1.0.0.1 with GHC 6. Typing :t at the GHCi prompt followed by the name of a function shows us the type of the function. Is there a way to view the function definition as well?
Not currently.
The closest command to what you want is :info
:info name ...
Displays information about the given name(s). For example, if name is a class, then the class methods and their types will be printed; if name is a type constructor, then its definition will be printed; if name is a function, then its type will be printed. If name has been loaded from a source file, then GHCi will also display the location of its definition in the source.
For types and classes, GHCi also summarises instances that mention them. To avoid showing irrelevant information, an instance is shown only if (a) its head mentions name, and (b) all the other things mentioned in the instance are in scope (either qualified or otherwise) as a result of a :load or :module commands.
like so:
Prelude> :info ($)
($) :: (a -> b) -> a -> b -- Defined in GHC.Base
infixr 0 $
You can though, see the source for identifiers generated by the haddock tool, on Hackage.
Look up the module on Hackage
Click on the source link
Note that "?src" is a valid command in lambdabot, on the #haskell IRC channel, and does what you'd expect.
> ?src ($)
> f $ x = f x
I don't think so. You can use :i for a little bit more information (more useful for infix operators and data constructions, etc.), but not the definition:
ghci> :i repeat
repeat :: a -> [a] -- Defined in GHC.List
You can use hoogle to quickly find the documentation for a standard library function, which on the right has a link to go to the source. It's still a few clicks away though.
Nope, can't do that. Some fun things you, the Haskell beginner, can do:
On the HTML haddock documents, click on "source"... study the source.
:browse to find all of the definitions exported by a module
Use :help for the obvious result
use the web interface of hoogle to search for functions, or install hoogle locally!
?
Profit!
I'm trying different data structures for implementing Prim's algorithm. So I made a class to abstract what I want to do:
class VertexContainer a where
contains :: a -> Vertex -> Bool
insert :: a -> WeightedEdge -> a
numVertices :: a -> Int
Now I want to use a heap (from Data.Heap) as my vertex container. But I can't for the life of me figure out the syntax. As you can see from the insert declaration, the container can only hold WeightedEdges, which are a data type. So I tried:
instance VertexContainer (Heap MinPolicy WeightedEdge) where
contains _ _ = True
It tells me it's an illegal type synonym. I've tried various other permutations, and none of them seem to work. Can anyone help me?
If you read the entire error message you'll find that it tells you how to be able to use a type synonym in an instance declaration, namely by using the language extension TypeSynonymInstances. E.g., you can pass -XTypeSynonymInstances on the command line.
I got it working by wrapping this into a newtype. Considered ugly. I guess you have to wait for one of the Haskell gurus to answer this.