I want to overload any operator . i want to do such a simple function that for instance think about overloading of == operator .Overload == such that
x==y
returns x .
Or x==y return x+y. It doesn't matter what . Can you show me any simple operator overloading example? I cannot find any example on the web unfortunately.
For example;when i call Tree a == Tree a
return 5 (it always return 5. I select it ,it is not related to any thing)
or when i call 3==4
return : 7
I tried the below codes(i find it from haskell.org) but it cannot compile.
class Eq a where
(==) ::a -> a -> Int
instance Eq Integer where
x == y = 5
instance Eq Float where
x == y = 5
Neither the below code works:
data Tree a = Node a | Empty
class Tree a where
(==) :: Tree a -> Tree a -> Int
instance Tree Integer where
x == y = 1
I take the error :
Ambiguous occurrence `Eq'
It could refer to either `Main.Eq', defined at Operations.hs:4:7
or `Prelude.Eq',
imported from `Prelude' at Operations.hs:1:1
(and originally defined in `GHC.Classes')
You can't hide instances from an imported module. See for example: Explicitly import instances
It looks like the "overloading" you're trying to do is to allow (==) for other types, like trees. This is easy! Just simply create a new instance:
data Tree a = Leaf a | Branch [Tree a]
instance (Eq a) => Eq (Tree a) where
(Leaf a) == (Leaf b) = a == b
(Branch a) == (Branch b) = a == b
_ == _ = False
(You could also just derive the Eq instance)
Try hiding the == from the Prelude first. You only need a type class if you want it to work differently for different types.
import Prelude hiding ((==))
x == y = x
Here's a +++ operator that acts like the (++) operator used to append lists:
(+++) :: [a]->[a]->[a]
x +++ [] = x
[] +++ x = x
x +++ y = (init x) +++ ((last x) : y)
Related
Im trying to write a little program that can check whether a given number appears in a Tree. This is my code:
import Prelude
data Tree = Node Int [Tree]
Tree happytree = Node 5 [Node 1 [Node 6 []],Node 8 [],Node 2 [Node 1 [],Node 4 []]]
contains1 :: [Tree] -> Int -> Bool
contains1 [] x = False
contains1 (a:as) x = contains a x || contains1 as x
contains :: Tree -> Int -> Bool
contains (Node x []) y = x==y
contains (Node x as) y = x==y || contains1 as y
Im getting the error message
Not in scope: data constructor ‘Tree’
Perhaps you meant ‘True’ (imported from Prelude)
What is this supposed to mean?
I was wondering if somebody could give me an advice how to write my contains function without writing the help function contains1.
Thanks in advance
You get the error from the declaration Tree happytree = .... It seems a C-style habit snuck into your code and you tried to declare the constant with a type in the wrong way.
It's just happytree = ... and the compiler deduces the type. If you want to specify it explicitly, you do it like with the functions and write happytree :: Tree on a separate line.
As for getting rid of contains1, it's testing whether any of the trees in the list contains the value, so you can get rid of it this way:
contains :: Tree -> Int -> Bool
contains (Node x []) y = x==y
contains (Node x as) y = x==y || any (`contains` y) as
I'm using section syntax here for the partially applied contains; you could instead write a lambda \a -> contains a y.
While Sebastian's answer tells you the problem (type declarations belong in their own lines), note that the error message stems from the following:
data Id Int = Id Int
Id x = Id 5
This is perfectly valid, since you're binding with a pattern Id x. It's similar to
(x:_) = [5..]
However, in order to do this, you need a data constructor, e.g. something that can create a value, like Node, whereas Tree is a type constructor, it creates (or in this case is) types. That's why you end up with that rather cryptic error message:
Not in scope: data constructor ‘Tree’
Perhaps you meant ‘True’ (imported from Prelude)
Either way, you can fix this by removing Tree from Tree happytree.
For your other question, use any:
contains :: Tree -> Int -> Bool
contains (Node x as) y = x == y || any (`contains` y) as
Note that elem-like functions (on lists elem :: Eq a => a -> [a] -> Bool) usually take the predicate first and the container last, which makes the application of contains easier:
contains :: Int -> Tree -> Bool
contains y (Node x as) = x == y || any (contains y) as
I'm trying to implement with Haskell an algorithm to manipulate mathematical expressions.
I have this data type :
data Exp = Var String | IVal Int | Add Exp Exp
This will be enough for my question.
Given a set of expression transformations, for example :
(Add a b) => (Add b a)
(Add (Add a b) c) => (Add a (Add b c))
And an expression, for example : x = (Add (Add x y) (Add z t)), I want to find all expressions in the neighborhood of x. Given that neighborhood of x is defined as: y in Neighborhood(x) if y can be reached from x within a single transformation.
I am new to Haskell. I am not even sure Haskell is the right tool for this job.
The final goal is to get a function : equivalent x which returns a set of all expressions that are equivalent to x. In other words, the set of all expressions that are in the closure of the neighborhood of x (given a set of transformations).
Right now, I have the following :
import Data.List(nub)
import Data.Set
data Exp = IVal Int
| Scalar String
| Add Exp Exp
deriving (Show, Eq, Ord)
commu (Add a b) = (Add b a)
commu x = x
assoc (Add (Add a b) c) = (Add a (Add b c))
assoc (Add a (Add b c)) = (Add (Add a b) c)
assoc x = x
neighbors x = [commu x, assoc x]
equiv :: [Exp] -> [Exp]
equiv closure
| closure == closureUntilNow = closure
| otherwise = equiv closureUntilNow
where closureUntilNow = nub $ closure ++ concat [neighbors x|x<-closure]
But It's probably slower than needed (nub is O(n^2)) and some terms are missing.
For example, if you have f = (x+y)+z, then, you will not get (x+z)+y, and some others.
Imports, etc. below. I'll be using the multiset package.
import Control.Monad
import Data.MultiSet as M
data Exp = Var String | IVal Int | Add Exp Exp deriving (Eq, Ord, Show, Read)
A bit of paper-and-pencil work shows the following fact: expressions e1 and e2 are in the congruence closure of your relation iff the multiset of leaves are equal. By leaves, I mean the Var and IVal values, e.g. the output of the following function:
leaves :: Exp -> MultiSet Exp
leaves (Add a b) = leaves a `union` leaves b
leaves e = singleton e
So this suggests a nice clean way to generate all the elements in a particular value's neighborhood (without attempting to generate any duplicates in the first place). First, generate the multiset of leaves; then nondeterministically choose a partition of the multiset and recurse. The code to generate partitions might look like this:
partitions :: Ord k => MultiSet k -> [(MultiSet k, MultiSet k)]
partitions = go . toOccurList where
go [] = [(empty, empty)]
go ((k, n):bag) = do
n' <- [0..n]
(left, right) <- go bag
return (insertMany k n' left, insertMany k (n-n') right)
Actually, we only want partitions where both the left and right part are non-empty. But we'll check that after we've generated them all; it's cheap, as there's only two that aren't like that per invocation of partitions. So now we can generate the whole neighborhood in one fell swoop:
neighborhood :: Exp -> [Exp]
neighborhood = go . leaves where
full = guard . not . M.null
go m
| size m == 1 = toList m
| otherwise = do
(leftBag, rightBag) <- partitions m
full leftBag
full rightBag
left <- go leftBag
right <- go rightBag
return (Add left right)
By the way, the reason you're not getting all the terms is because you're generating the reflexive, transitive closure but not the congruence closure: you need to apply your rewrite rules deep in the term, not just at the top level.
So I'm trying to define a function in Haskell that if given an integer and a list of integers will give a 'true' or 'false' whether the integer occurs only once or not.
So far I've got:
let once :: Eq a => a -> [a] -> Bool; once x l =
But I haven't finished writing the code yet. I'm very new to Haskell as you may be able to tell.
Start off by using pattern matching:
once x [] =
once x (y:ys) =
This won't give you a good program immediately, but it will lead you in the right direction.
Here's a solution that doesn't use pattern matching explicitly. Instead, it keeps track of a Bool which represents if a occurance has already been found.
As others have pointed out, this is probably a homework problem, so I've intentionally left the then and else branches blank. I encourage user3482534 to experiment with this code and fill them in themselves.
once :: Eq a => a -> [a] -> Bool
once a = foldr f False
where f x b = if x == a then ??? else ???
Edit: The naive implementation I was originally thinking of was:
once :: Eq a => a -> [a] -> Bool
once a = foldr f False
where f x b = if x == a then b /= True else b
but this is incorrect as,
λ. once 'x' "xxx"
True
which should, of course, be False as 'x' occurs more than exactly once.
However, to show that it is possible to write once using a fold, here's a revised version that uses a custom monoid to keep track of how many times the element has occured:
import Data.List
import Data.Foldable
import Data.Monoid
data Occur = Zero | Once | Many
deriving Eq
instance Monoid Occur where
mempty = Zero
Zero `mappend` x = x
x `mappend` Zero = x
_ `mappend` _ = Many
once :: Eq a => a -> [a] -> Bool
once a = (==) Once . foldMap f
where f x = if x == a then Once else Zero
main = do
let xss = inits "xxxxx"
print $ map (once 'x') xss
which prints
[False,True,False,False,False]
as expected.
The structure of once is similar, but not identical, to the original.
I'll answer this as if it were a homework question since it looks like one.
Read about pattern matching in function declarations, especially when they give an example of processing a list. You'll use tools from Data.List later, but probably your professor is teaching about pattern matching.
Think about a function that maps values to a 1 or 0 depending on whethere there is a match ...
match :: a -> [a] -> [Int]
match x xs = map -- fill in the thing here such that
-- match 3 [1,2,3,4,5] == [0,0,1,0,0]
Note that there is the sum function that takes a list of numbers and returns the sum of the numbers in the list. So to count the matches a function can take the match function and return the counts.
countN :: a -> [a] -> Int
countN x xs = ? $ match x xs
And finally a function that exploits the countN function to check for a count of only 1. (==1).
Hope you can figure out the rest ...
You can filter the list and then check the length of the resulting list. If length == 1, you have only one occurrence of the given Integer:
once :: Eq a => a -> [a] -> Bool
once x = (== 1) . length . filter (== x)
For counting generally, with import Data.List (foldl'), pointfree
count pred = foldl' (\ n x -> if pred x then n + 1 else n) 0
applicable like
count (< 10) [1 .. 10] == 9
count (== 'l') "Hello" == 2
gives
once pred xs = count pred xs == 1
Efficient O(n) short-circuit predicated form, testing whether the predicate is satisfied exactly once:
once :: (a -> Bool) -> [a] -> Bool
once pred list = one list 0
where
one [] 1 = True
one [] _ = False
one _ 2 = False
one (x : xs) n | pred x = one xs (n + 1)
| otherwise = one xs n
Or, using any:
none pred = not . any pred
once :: (a -> Bool) -> [a] -> Bool
once _ [] = False
once pred (x : xs) | pred x = none pred xs
| otherwise = one pred xs
gives
elemOnce y = once (== y)
which
elemOnce 47 [1,1,2] == False
elemOnce 2 [1,1,2] == True
elemOnce 81 [81,81,2] == False
import Data.Function (on)
import Data.List (sort)
data Monomial = Monomial
{ m_coeff :: Coefficient
, m_powers :: [(Variable, Power)]
}
deriving ()
instance Ord Monomial where
(>=) = on (>=) m_powers
instance Eq Monomial where
(==) = on (==) m_powers
That's an excerpt from my code, cut down to principal size. Let's try comparing:
*Main> (Monomial 1 [("x",2)]) > (Monomial (-1) [])
/* Computation hangs here */
*Main> (Monomial 1 [("x",2)]) < (Monomial (-1) [])
/* Computation hangs here */
On a side note, it's interesting that if I replace s/(>=)/(>)/g in instance declaration, it will not hang on the fist pair, but still will on the second:
*Main> (Monomial 1 [("x",2)]) > (Monomial (-1) [])
True
*Main> (Monomial 1 [("x",2)]) < (Monomial (-1) [])
/* Computation hangs here */
Although the standard states minimal declaration of Eq instance to be either$compare$ or $(>=)$.
What might be the problem here? (>=) on lists seems to work just fine.
Short answer:
You need to provide either (<=) or compare to have a complete definition for Ord, not (>=).
Longer explanation:
It is common for type classes in Haskell to have default implementations of some methods implemented in terms of other methods. You can then choose which ones you want to implement. For example, Eq looks like this:
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)
Here, you must either implement (==) or (/=), otherwise trying to use either of them will cause an infinite loop. Which methods you need to provide is usually listed as the minimal complete definition in the documentation.
The minimal complete definition for Ord instances, as listed in the documentation, is either (<=) or compare. Since you've only provided (>=), you have not provided a complete definition, and therefore some of the methods will loop. You can fix it by e.g. changing your instance to provide compare instead.
instance Ord Monomial where
compare = compare `on` m_powers
Let's look at the default instance for Ord:
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y = if x == y then EQ
-- NB: must be '<=' not '<' to validate the
-- above claim about the minimal things that
-- can be defined for an instance of Ord:
else if x <= y then LT
else GT
x < y = case compare x y of { LT -> True; _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x > y = case compare x y of { GT -> True; _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }
-- These two default methods use '<=' rather than 'compare'
-- because the latter is often more expensive
max x y = if x <= y then y else x
min x y = if x <= y then x else y
So, if you supply >= and == as above, only, then you are in trouble, since:
> is defined in terms of compare
But
compare is defined in terms of <=
<= is defined in terms of compare
So you have an infinite loop!
A minimum definition must defined <= or compare, not '>=`.
Ok so we have not learned polymorphic functions yet, but we still have to write this code.
Given:
nameEQ (a,_) (b,_) = a == b
numberEQ (_,a) (_,b) = a == b
intEQ a b = a == b
member :: (a -> a -> Bool) -> a -> [a] -> Bool
I added:
member eq x ys | length ys < 1 = False
| head(ys) == x = True
| otherwise = member(x,tail(ys))
but i get errors about not being the correct type as well as some other stuff. We have to see if an element exists in from some type. So we have those 2 types above. Some examples given:
phoneDB = [("Jenny","867-5309"), ("Alice","555-1212"), ("Bob","621-6613")]
> member nameEQ ("Alice","") phoneDB
True
> member nameEQ ("Jenny","") phoneDB
True
> member nameEQ ("Erica","") phoneDB
False
> member numberEQ ("","867-5309") phoneDB
True
> member numberEQ ("","111-2222") phoneDB
False
> member intEQ 4 [1,2,3,4]
True
> member intEQ 4 [1,2,3,5]
False
not exactly sure what i need to do here. Any help or documentation on this would be great. Thanks!
Various things (I'm not going to write out the full answer as this is homework):
length ys < 1 can be more simply expressed as null ys
You don't need brackets around function arguments. head(ys) is more commonly written as head ys
You can, if you want, turn the top case and the other two into pattern matches rather than guards. member eq x [] = ... will match the empty case, member eq x (y:ys) = ... will match the non-empty case.
You are using == for comparison. But you're meant to use the eq function you're given instead.
You are bracketing the arguments to member as if this was Java or similar. In Haskell, arguments are separated by spaces, so member(x,(tail(ys)) should be member x (tail ys).
Those errors you gloss over "about not being the correct type as well as some other stuff" are important. They tell you what's wrong.
For example, the first time I threw your code into ghc I got:
Couldn't match expected type `a -> a -> Bool'
against inferred type `(a1, [a1])'
In the first argument of `member', namely `(x, tail (ys))'
In the expression: member (x, tail (ys))
In the definition of `member':
member eq x ys
| length ys < 1 = False
| head (ys) == x = True
| otherwise = member (x, tail (ys))
Well, when I look at it that's straightforward - you've typed
member(x,tail(ys))
When you clearly meant:
member x (tail ys)
Commas mean something in Haskell you didn't intend there.
Once I made that change it complained again that you'd left off the eq argument to member.
The error after that is tougher if you haven't learned about Haskell typeclasses yet, but suffice it to say that you need to use the passed-in eq function for comparing, not ==.
Since the parameters a in member :: (a -> a -> Bool) -> a -> [a] -> Bool
don't derive Eq, you can't use == to compare them,
but instead have to use the given function eq.
Therefore your code might look like this:
member :: (a -> a -> Bool) -> a -> [a] -> Bool
member eq x ys
| length ys < 1 = False
| eq x (head ys) = True
| otherwise = member eq x (tail ys)
Only problem with this is, that length still requires to evaluate the entire List,
so you could reach a a better performance writing:
member' :: (a -> a -> Bool) -> a -> [a] -> Bool
member' eq x (y:ys)
| eq x y = True
| otherwise = member' eq x ys
member' _ _ [] = False
With the use of any you can simplify it even more:
member'' :: (a -> a -> Bool) -> a -> [a] -> Bool
member'' f a = any (f a)