Haskell, how to convert ADT to String? [closed] - haskell

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
here is my ADT:
data Tree a = Val Integer
|Tree a
|Variable a
I have two questions:
Question 1: use Tree String type to represent some trees?
Question 2: define a function for converting a tree, an element of the datatype Tree String to string: showTree::Tree String -> String

With respect to your second question, coverting a tree into a string, just derive Show and use the show function:
data Tree a = Val Integer
| Tree a
| Variable a
deriving (Eq, Ord, Show)
showTree :: (Show a) => Tree a -> String
showTree = show
I don't understand your first question, so I'm just going to talk a bit in hopes that something I say helps you.
Understand that your "tree" data type is not really a tree at all, it's just a sum data type that can be instantiated by an integer or some type that matches the type variable, a. The second constructor, Tree, is actually not making your data type recursive - its just a constructor name in the same way Variable is a constructor name. I think you probably wanted to have subtrees (by using Tree as a type, not a constructor) - so let's define your type as:
data Tree a = Val Integer
| Branch (Tree a) (Tree a)
| Variable a
Now you have a constructor named Branch that has a left and a right sub-tree. If your variables are supposed to be Strings then you certainly can use Tree String to represent this:
myTree :: Tree String
myTree =
let leftBranch = Variable "x"
rightBranch = Branch (Val 3) (Variable "y")
in Branch leftBranch rightBranch

Related

Binary Trees Haskell

So i have this data structure:
class ordering a where
order :: a-> Int
And i want to create a search tree, where every node is a list of elements, specified by their own order number( root is 1, root of left subtree is 2, root of right subtree is 3, and so on..). Every type of data that is inserted in the tree has an "order" number associated with it that only matters for "tree insertion purposes", and if it is equal to 1, it stays in the root, if it is two, it stays on the left side of the tree, and so on..
Here's my attempt at this:
data Tree a = EmptyTree
| Node a order a (Tree [a]) (Tree [a]) deriving (Show, Read, Eq)
What i've done, makes sense to me, but apparently is wrong, but honestly i have no idea why...
I'm new to Haskell, and i've been struggling to learn the language, so i appreciate any kind of help from you guys!
The ordering that you have defined is a type class, not a data structure. order is an operation, not a type. Putting the order operation in the Tree data structure makes no sense.
You also haven't shown us any code to actually insert data, so I'm unsure how this is supposed to work.
Let's start from the function actually. Apparently you want this:
insert :: Ord key => (key,val) -> Tree key val -> Tree key val
since your tree carries values that are to be inserted according to keys, this Tree type must enclose both of them:
data Ord key => Tree key val = EmptyTree
| Node key val (Tree key val) (Tree key val)
now it's easy to implement the insert function. Each tree of a type Tree key val will be able to carry keys of type key and values of type val. To accommodate for various concrete value types in one tree you can use a tagged union type for it:
data Myval = My_c1 | My_c2 | MyInt Int | MyInts [Int] | MyString String | ...
now a tree of type, e.g., Tree Int Myval will carry values tagged with Myval constructors, inserted according to the user supplied Int keys.
If you mean that every data type has its own key,
ordkey :: Myval -> Int
ordkey My_c1 = 1
ordkey My_c2 = 2
ordkey (MyInt _) = 3
....
then you won't use insert directly, but rather through an intermediary,
ordinsert val tree = insert (ordkey val,val) tree
This is of course a simple, unsophisticated way to go about it, maybe this is what you meant.

understanding types [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am learning Haskell and I want to understand types. Assume that I have an object of type Store:
import Data.Map (Map)
import qualified Data.Map as Map
type Variable = String
data Value = IntVal Int
| BoolVal Bool
type Store = Map Variable Value
How can use this object, say s to get value of variable?
And how to save value of a variable in Store?
In a type declaration, the token on the left of the = is the type's name. Values to the right of the = define constructors - functions that create an instance of that type.
Consider the definition of Maybe, a simple type that represents the possibility of a failure (represented as null or nil in many languages):
data Maybe a = Just a | Nothing
This is a type with two constructors: Just and Nothing:
The Just constructor represents success. It requires an argument of any type, representing the value to wrap
The Nothing constructor takes no arguments. It represents failure.
You can see here that because Maybe has two constructors, there are two ways of constructing Maybe values. Such types are called union types. You extract values from union types using pattern matching. There are several language constructs that allow pattern matching (let and where-bindings, case statements, and function variable bindings). Below, we destructure a Just value in the arguments to a function.
fromJust :: Maybe a -> a
fromJust (Just x) = x
Assume this is loaded into GHCI. Here, we create an instance of Maybe, using the Just constructor, then retrieve that value again:
> let x = Just 20
> fromJust x
20
Here's how pattern matching looks for your types. We create an instance of the Store type using the Map constructor you've defined:
> let m = Map "someVar" $ IntVal 0
Below we define a function that will extract the Variable value from a Map.
getVariable :: Store -> Variable
getVariable (Map v _) = v
Applying the function:
> getVariable m
"someVar"
Hopefully the resources you're learning from will cover this stuff soon. If not, I recommend a dose of Real World Haskell.
Here's some example usage:
s :: Store
s = fromList [("key1", IntVal 4), ("key2", BoolVal False)]
lookup "key1" s -- Just (IntVal 4)
lookup "key2" s -- Just (BoolVal False)
lookup "key3" s -- Nothing
s' :: Store
s' = insert "key3" (BoolVal True) s
lookup "key3" s' -- Just (BoolVal True)

A Simple Haskell Operator [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
For my assignment, we have to write a primitive function which looks like this:
My question is Prim Eq, Prim Less, Prim Great should be able to take any kinds of parameters such as String, Number although its return type is always boolean... So I am not sure how to specify the types a and b.
If you know how to approach this, please let me know. I'd really appreciate your help.
Thank you very much.
prim Less [Number a, Number b] = Bool (a < b)
prim Less [String a, String b] = Bool (a < b)
prim Great [Number a, Number b] = Bool (a > b)
prim Great [String a, String b] = Bool (a > b)
a and b are not types; they're values. I'm not sure what you want to specify here.
What you want to look at is GADTs. However you maybe won't be able to have your prim function, but you can get more type safety if you could add type signatures to constructors, like Eq :: Value a -> Value a -> Value Bool and the way to do this is GADTs.

Haskell, creating a structured datatype [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I would like to create a structure datatype called Structured that can be used to represent String, Int and List. For example, structure is like: [Int, String, Int,[Int]].
Question 1: how to create this datatype?
data Structured = ...
Question 2: A function called Confirm that confirms the input satisfies a restriction, and has the signature type of confirm:: Restriction -> Structure ->Maybe Bool
data Structured = Structured Int String Int [Int]
would work.
confirm :: (Structured -> Bool) -> Structured -> Bool
seems a more sensible type, but has a trivial implementation as id.
I don't think you would need to return Maybe Bool from a valudation function - Maybe a is good for when you usually resturn an a, but sometimes don't. (It's good for very simple error handling, for example - give Nothing if there was an error.) In this case, you can always make a conclusion as to whether your input was valid, so you can always give back True or False - no need for the Maybe.
Perhaps you could have something like
confirm :: (String -> Bool) -> (Int -> Bool) -> Structured -> Bool
confirm okString okInt (Structured int1 string int2 ints) =
all okInt (int1:int2:ints) && okString string
Here int1:int2:ints is the list that has int1 in front of int2 in front of ints.
A slightly nicer way of defining Structured would be:
data Structured = Structured {
length ::Int,
name ::String,
width ::Int,
somenumbers :: [Int]}
then you'd have
confirm :: (String -> Bool) -> (Int -> Bool) -> Structured -> Bool
confirm okString okInt s =
all okInt (length s:width s:somenumbers s) && okString (name s)
It does the same job as the first data declaration, but gives you functions for getting at the internals.

overloading in different programming languages [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Can somebody please explain (with example) the difference between context-independent and context-dependent overloading?
I have never heard about those. And there's only about five hits on Google, one of which is this very question, which seems to suggest to me that these are made-up terms. And as with any made-up term, if you want to know what it means, you have to ask the person who made it up.
From what little I could gather, it seems to be related to return-type based overloading.
Basically, if you have four overloaded functions like these:
foo :: string → int
foo :: string → string
foo :: string → ()
foo :: int → int
And you call them like this:
1 + foo 1
1 + foo "one"
foo "one"
Then, with context-dependent overloading (i.e. overloading based on the return type as well as the parameter types), the following implementations will be selected:
1 + foo 1 # foo :: int → int
1 + foo "one" # foo :: string → int (because `+` takes an `int`)
foo "one" # foo :: string → () (because there is no return value)
Whereas with context-independent overloading (i.e. ignoring the return type), the following implementations will be selected:
1 + foo 1 # foo :: int → int
1 + foo "one" # ERROR
foo "one" # ERROR
In both the ERROR cases, there is an ambiguity between foo :: string → int, foo :: string → string and foo :: string → (), since they only differ in their return type but have the same paremeter type.
Quoting from here:
There are two kinds of overloading of
functions/operators.
context-independent - overloading only done on parameters to
function or type of operands for an
operator
context-dependent - which abstraction to call also depends upon
the type of the result

Resources