text:
# How to derive the equation of a parabola given a focus and a directrix not parallel to the x or y axis?

I was wondering if it is possible to derive a general form of a parabola given any focus and directrix.

So far all the materials I have come across only show the derivation for a parabola equation where the directrix is $x=c$ or $y=c$ for some constant $c$. And the only material I know that provides a general formula for a parabola is this article in wikipedia. But this relies on the general form of the conic equation.

I would like to derive the general equation of the parabola based on the definition of the parabola:

Let:

$d_1$ be the distance of a point on the parabola and its focus, $P(x_1,y_1)$

$d_2$ be the distance of a point on the parobola to its directrix, $y=mx+c$

$P(x,y)$ be any point on the parabola

So by definition of a parabola, \begin{align} d_1 &= d_2 \\ \sqrt{(x-x_1)^2 - (x-y_1)^2 } &= ??\end{align}

I can't proceed further as I don't know what to put for $d_2$ as all the textbook I consulted only have the directrix in the form of $x=c$ or $y=c$, which leads me to think that a derivation of the general parabola equation using this approach is impossible.

-
Do you know linear algebra? If so, the easiest way would be to find the equation of the parabola when the directrix is of the form $x=c$ (or $y=c$) and rotate the coordinate system. – Étienne Bézout Oct 10 '13 at 14:33
In analytic geometry one studies the following formula for the point-line distance $$d=\frac {|ax_0+by_0+c|}{\sqrt{a^2+b^2}}$$ – Tony Piccolo Oct 10 '13 at 14:42
@ÉtienneBézout I do know linear algebra. But like to solve it using this approach first. So I gather from your comment that this approach is feasible but tedious. Which part of it is tedious? – mauna Oct 10 '13 at 14:44
@mauna I recall attempting your approach a few years ago in my linear algebra course, and I think it resulted in some equations which were rather tedious to solve. Also, if you try to take a general directrix on the form $y=mx+c$ you will not cover the case of vertical directrices. In your approach, it is probably best to write the directrix on the form $ax+by+c=0$ and follow Tony Piccolo's suggestion. – Étienne Bézout Oct 10 '13 at 14:50
I would recommend equating the squares of the distances, which gets rid of the square roots and absolute values. Also the equation with the square root and two question marks looks a bit mixed up to me - I'm not sure what the left-hand side is supposed to be. – Mark Bennet Oct 10 '13 at 15:59

$$d_1=\sqrt{(x-x_1)^2+(y-y_1)^2}$$ And $$d_2=\frac{|y-mx+c|}{\sqrt{1+m^2}}$$ You can form the equation of Parabola now, but as you were unsure about second, I'll help you prove it:

As we are measuring perpendicular distance, take the line perpendicular to $y=mx+c$ passing through $(x_0,y_0)$ and the foot of perpendicular on line $(\alpha,\beta)$,i.e.$$(\beta-y_0)=\frac{-1}m(\alpha-x_0)$$ Or, $$m(\beta-y_0)+(\alpha-x_0)=0$$ Squaring, $$m^2(\beta-y_0)^2+(\alpha-x_0)^2=-2m(\alpha-x_0)(\beta-y_0)\tag1$$ Now consider, $$(m(\alpha-x_0)-(\beta-y_0))^2=m^2(\alpha-x_0)^2+(\beta-y_0)^2-2m(\alpha-x_0)(\beta-y_0)$$ Or $$m^2(\alpha-x_0)^2+(\beta-y_0)^2-(m(\alpha-x_0)-(\beta-y_0))^2=2m(\alpha-x_0)(\beta-y_0)\tag2$$ Adding (1) and (2), $$m^2(y-y_0)^2+(\alpha-x_0)^2+m^2(\alpha-x_0)^2+(\beta-y_0)^2=(m(\alpha-x_0)-(\beta-y_0))^2$$ Or [Use $c=\beta-m\alpha$ and rearrange] $$(m^2+1)((\beta-y_0)^2+(\alpha-x_0)^2)=(y_0-mx_0-c)^2$$ So distance from line is: $$d=\sqrt{(\beta-y_0)^2+(\alpha-x_0)^2}=\frac{|(y_0-mx_0-c)^2|}{m^2+1}$$ Note: For a line $ax+by=c$, put $m=-\frac ab$ to get: $$d=\frac {|ax_0+by_0+c|}{\sqrt{a^2+b^2}}$$

-

Let:

$d_1$ be the distance of a point on the parabola and its focus, $P(x1,y1)$ $d_2$ be the distance of a point on the parobola to its directrix, $y=mx+c$ $P(x,y)$ be any point on the parabola

So by definition of a parabola, $$d_1=\sqrt{(x−x_1)^2−(x−y_1)^2}=d_2$$.

$$(Y-y_1)=A(X-x_1)^2$$ where $A=$the degree and direction of parabola i.e. $-x^2$ is downward

$(y_1,x_1)$ is focus and directrix is $y=c=1/4A$

Derived from all points equidistant from focus to any $x,y$ and directrix, as formal definition of a parabola, from Pythagorean theorem

$$(X-a)^2+(Y-b)^2=(Y-c)^2$$

Separate $y$ values to one side and expand

$$(X-a)^2=Y^2-Y^2+2Yb-2Yc-b^2+c^2 =2Y(b-c)-(b^2-c^2)\\ (X-a)^2=2Y(b-c)-((b-c)(b+c))\\ (X-a)^2/(2(b-c))=Y-(b+c).$$ So $$A=\frac 12(b-c) \text{ and } x_1=a, y_1=b \text{ and }c=\text{ directrix}$$

Kind of one way to do I guess. Sure there is less convoluted solution to it but once you understand this you will get better.

-
[How to format maths here] (meta.math.stackexchange.com/questions/5020/…) – ADG Aug 9 '14 at 7:37

The equation of the parabola using your notation is

\begin{multline} x^2 + m^2\,y^2 + 2m\,xy \\ {}- 2\bigl(x_1(1+m^2)+mc\bigr)\,x {}- 2\bigl(y_1(1+m^2)-c\bigr)\,y \\ + \bigl((x_1^2+y_1^2)(1+m^2)-c^2\bigr) =0 \end{multline}

In the derivation below I'll change the notation to avoid the indices and to make the situation more generic with respect to the equation of the line. I'll write the focus as $F=(x,y)$ and the directrix using the equation $aX+bY+c=0$ (as Étienne Bézout suggested). So $(X,Y)$ denotes a generic point against which a certain equation can be tested. My $x$ is your $x_1$, my $y$ your $y_1$, and since your line is $mx-y+c=0$, my $a$ is your $m$, my $b$ is $-1$ and my $c$ agrees with yours.

The vector $(a,b)$ denotes the direction orthogonal to the directrix. So the point on the directrix closest to a given point $(X,Y)$ is $(X,Y)+\lambda(a,b)=(X+\lambda a,Y+\lambda b)$ with $\lambda$ chosen such that it satisfies the equation of the line, namely

\begin{align*} a(X+\lambda a)+b(Y+\lambda b)+c&=0 \\ \lambda&=-\frac{a\,X+b\,Y+c}{a^2+b^2} \end{align*}

If you had the equation of the line scaled such that $a^2+b^2=1$, then this $\lambda$ would already be the length $d_2$. Otherwise, you have to multiply it by $\lVert(a,b)\rVert=\sqrt{a^2+b^2}$ (since your distance vector is $\lambda(a,b)$ so it has length $d_2=\lambda\lVert(a,b)\rVert$). You will find the length to be (like Tony Piccolo already stated):

$$d_2=\left|\frac{a\,X+b\,Y+c}{\sqrt{a^2+b^2}}\right|$$

Now that absolute value and that square root is ugly, so I'd square both sides (as suggested by Mark Bennet):

\begin{align*} d_1^2 &= d_2^2 \\ (X-x)^2+(Y-y)^2 &= \frac{(a\,X+b\,Y+c)^2}{a^2+b^2} \\ \bigl(a^2+b^2\bigr)\bigl((X-x)^2+(Y-y)^2\bigr) &= (a\,X+b\,Y+c)^2 \\ \bigl(a^2+b^2\bigr)\bigl((X-x)^2+(Y-y)^2\bigr) - (a\,X+b\,Y+c)^2 &= 0 \end{align*}

If you expand this and then collect terms with common powers of $X,Y$, you end up with the equation given initially, except for the change in notation:

\begin{multline} b^2\,X^2 + a^2\,Y^2 - 2ab\,XY \\ {}- 2\bigl(x(a^2+b^2)+ac\bigr)\,X {}- 2\bigl(y(a^2+b^2)+bc\bigr)\,Y \\ + \bigl((x^2+y^2)(a^2+b^2)-c^2\bigr) =0 \end{multline}

I first dealt with this whole situation in a different context, obtaining the formula using a different description of the parabola. But it's nice to see it confirmed like this.

-


text:
Charge on the nucleus

1. Sep 15, 2005

I've got this following question which I don't really get:

What is the charge on the nucleus of each of the following? (assuming they are neutral)

a) Mg b) Ne c) K^+ d) S^2-

What I don't understand is the definition of "charge on the nucleus"

I am assuming that only protons have charge in the nucleus, therefore, I just count the number of protons and that gives me the charge on the nucleus.

This is what I think I'm supposed to do:

a) +12 b) +10 c) +19 d) +16

But then, would the charge be zero, because the electrons end up canceling the charge from the protons?

Or is there another way I'm supposed to do this?

Thanks,

Jason

Last edited: Sep 15, 2005
2. Sep 16, 2005

mind game

effective nuclear charge is the charge felt by the valence electrons after you have taken into account the number of shielding electrons that surround the nucleus.

since u have given in brackets that assuming these atoms are neutral for clearence of ur concept let's take a look at a fluorine atom.The nucleus itself has a +9 charge and anything in its vicinity will feel that charge. The two electrons in the first energy level as they look at the nucleus feel a +9 charge because that is the charge on the nucleus.assuming the atom to b neutral there would be 9 electrons as a whole in atom and 7 electron in secoind or valence energy level electrons that are in the valence energy level would be shielded from the nucleus by the 2 shielding electrons(in 1st energy level) The +9 nuclear charge is shielded by 2 electrons to give an effective nuclear charge of +7 that is felt by the valence electrons
but If you get out beyond the valence electrons, then the effective charge is 0 simply because the +9 charge of the nucleus is surrounded by 9 electrons.
now u can easily solve K +1 charge and also -2 charge as the show that one electron is removed and 2 are added respectively

Last edited: Sep 16, 2005
3. Sep 16, 2005

whozum

The charge on the nucleus is the sum of the charge of each proton's +1. I think this is what the question is asking. The answer to your second question is no, because some of the elements are not in their neutral form (c and d), thus are missing an electron (c) or have electrons in excess (d), so their total charge is not 0.

If its asking for effective nuclear charge, then you want to find the charge of the protons minus the charge of all non-valence electrons.

4. Sep 16, 2005

Diane_

This may be a very easy question, depending on how accurately you've reported it. If the question is the charge on the nucleus, then the state of the electrons is irrelevant - they aren't in the nucleus. Consequently, you just go with the number of protons.

Note that this is true even for the ions you mention in (c) and (d). Ions gain their charges by gaining or losing electrons, but the charge on the nucleus cannot change without changing the element involved. If it's potassium you're talking about, then it'll have the same nuclear charge whether the atom itself is ionized or not.

So, again: if you've reported the question accurately, then the answer is as close as your periodic table.

format: plain


text:
containers-0.5.11.0: Assorted concrete container types

Data.Map.Lazy

Description

# Finite Maps (lazy interface)

The Map k v type represents a finite map (sometimes called a dictionary) from keys of type k to values of type v. A Map is strict in its keys but lazy in its values.

The functions in Data.Map.Strict are careful to force values before installing them in a Map. This is usually more efficient in cases where laziness is not essential. The functions in this module do not do so.

When deciding if this is the correct data structure to use, consider:

• If you are using Int keys, you will get much better performance for most operations using Data.IntMap.Lazy.
• If you don't care about ordering, consider using Data.HashMap.Lazy from the unordered-containers package instead.

For a walkthrough of the most commonly used functions see the maps introduction.

This module is intended to be imported qualified, to avoid name clashes with Prelude functions:

import qualified Data.Map.Lazy as Map

Note that the implementation is generally left-biased. Functions that take two maps as arguments and combine them, such as union and intersection, prefer the values in the first argument to those in the second.

## Detailed performance information

The amortized running time is given for each operation, with n referring to the number of entries in the map.

Benchmarks comparing Data.Map.Lazy with other dictionary implementations can be found at https://github.com/haskell-perf/dictionaries.

## Warning

The size of a Map must not exceed maxBound::Int. Violation of this condition is not detected and if the size limit is exceeded, its behaviour is undefined.

## Implementation

The implementation of Map is based on size balanced binary trees (or trees of bounded balance) as described by:

• Stephen Adams, "Efficient sets: a balancing act", Journal of Functional Programming 3(4):553-562, October 1993, http://www.swiss.ai.mit.edu/~adams/BB/.
• J. Nievergelt and E.M. Reingold, "Binary search trees of bounded balance", SIAM journal of computing 2(1), March 1973.

Bounds for union, intersection, and difference are as given by

Synopsis

# Map type

data Map k a Source #

A Map from keys k to values a.

Instances

 Source # Since: 0.5.9 MethodsliftEq2 :: (a -> b -> Bool) -> (c -> d -> Bool) -> Map a c -> Map b d -> Bool # Source # Since: 0.5.9 MethodsliftCompare2 :: (a -> b -> Ordering) -> (c -> d -> Ordering) -> Map a c -> Map b d -> Ordering # Source # Since: 0.5.9 MethodsliftShowsPrec2 :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> Int -> Map a b -> ShowS #liftShowList2 :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> (Int -> b -> ShowS) -> ([b] -> ShowS) -> [Map a b] -> ShowS # Functor (Map k) Source # Methodsfmap :: (a -> b) -> Map k a -> Map k b #(<$) :: a -> Map k b -> Map k a # Foldable (Map k) Source # Methodsfold :: Monoid m => Map k m -> m #foldMap :: Monoid m => (a -> m) -> Map k a -> m #foldr :: (a -> b -> b) -> b -> Map k a -> b #foldr' :: (a -> b -> b) -> b -> Map k a -> b #foldl :: (b -> a -> b) -> b -> Map k a -> b #foldl' :: (b -> a -> b) -> b -> Map k a -> b #foldr1 :: (a -> a -> a) -> Map k a -> a #foldl1 :: (a -> a -> a) -> Map k a -> a #toList :: Map k a -> [a] #null :: Map k a -> Bool #length :: Map k a -> Int #elem :: Eq a => a -> Map k a -> Bool #maximum :: Ord a => Map k a -> a #minimum :: Ord a => Map k a -> a #sum :: Num a => Map k a -> a #product :: Num a => Map k a -> a # Source # Methodstraverse :: Applicative f => (a -> f b) -> Map k a -> f (Map k b) #sequenceA :: Applicative f => Map k (f a) -> f (Map k a) #mapM :: Monad m => (a -> m b) -> Map k a -> m (Map k b) #sequence :: Monad m => Map k (m a) -> m (Map k a) # Eq k => Eq1 (Map k) Source # Since: 0.5.9 MethodsliftEq :: (a -> b -> Bool) -> Map k a -> Map k b -> Bool # Ord k => Ord1 (Map k) Source # Since: 0.5.9 MethodsliftCompare :: (a -> b -> Ordering) -> Map k a -> Map k b -> Ordering # (Ord k, Read k) => Read1 (Map k) Source # Since: 0.5.9 MethodsliftReadsPrec :: (Int -> ReadS a) -> ReadS [a] -> Int -> ReadS (Map k a) #liftReadList :: (Int -> ReadS a) -> ReadS [a] -> ReadS [Map k a] # Show k => Show1 (Map k) Source # Since: 0.5.9 MethodsliftShowsPrec :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> Int -> Map k a -> ShowS #liftShowList :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> [Map k a] -> ShowS # Ord k => IsList (Map k v) Source # Since: 0.5.6.2 Associated Typestype Item (Map k v) :: * # MethodsfromList :: [Item (Map k v)] -> Map k v #fromListN :: Int -> [Item (Map k v)] -> Map k v #toList :: Map k v -> [Item (Map k v)] # (Eq k, Eq a) => Eq (Map k a) Source # Methods(==) :: Map k a -> Map k a -> Bool #(/=) :: Map k a -> Map k a -> Bool # (Data k, Data a, Ord k) => Data (Map k a) Source # Methodsgfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Map k a -> c (Map k a) #gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Map k a) #toConstr :: Map k a -> Constr #dataTypeOf :: Map k a -> DataType #dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c (Map k a)) #dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Map k a)) #gmapT :: (forall b. Data b => b -> b) -> Map k a -> Map k a #gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Map k a -> r #gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Map k a -> r #gmapQ :: (forall d. Data d => d -> u) -> Map k a -> [u] #gmapQi :: Int -> (forall d. Data d => d -> u) -> Map k a -> u #gmapM :: Monad m => (forall d. Data d => d -> m d) -> Map k a -> m (Map k a) #gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Map k a -> m (Map k a) #gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Map k a -> m (Map k a) # (Ord k, Ord v) => Ord (Map k v) Source # Methodscompare :: Map k v -> Map k v -> Ordering #(<) :: Map k v -> Map k v -> Bool #(<=) :: Map k v -> Map k v -> Bool #(>) :: Map k v -> Map k v -> Bool #(>=) :: Map k v -> Map k v -> Bool #max :: Map k v -> Map k v -> Map k v #min :: Map k v -> Map k v -> Map k v # (Ord k, Read k, Read e) => Read (Map k e) Source # MethodsreadsPrec :: Int -> ReadS (Map k e) #readList :: ReadS [Map k e] #readPrec :: ReadPrec (Map k e) #readListPrec :: ReadPrec [Map k e] # (Show k, Show a) => Show (Map k a) Source # MethodsshowsPrec :: Int -> Map k a -> ShowS #show :: Map k a -> String #showList :: [Map k a] -> ShowS # Ord k => Semigroup (Map k v) Source # Methods(<>) :: Map k v -> Map k v -> Map k v #sconcat :: NonEmpty (Map k v) -> Map k v #stimes :: Integral b => b -> Map k v -> Map k v # Ord k => Monoid (Map k v) Source # Methodsmempty :: Map k v #mappend :: Map k v -> Map k v -> Map k v #mconcat :: [Map k v] -> Map k v # (NFData k, NFData a) => NFData (Map k a) Source # Methodsrnf :: Map k a -> () # type Item (Map k v) Source # type Item (Map k v) = (k, v) # Operators (!) :: Ord k => Map k a -> k -> a infixl 9 Source # O(log n). Find the value at a key. Calls error when the element can not be found. fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map fromList [(5,'a'), (3,'b')] ! 5 == 'a' (!?) :: Ord k => Map k a -> k -> Maybe a infixl 9 Source # O(log n). Find the value at a key. Returns Nothing when the element can not be found. fromList [(5, 'a'), (3, 'b')] !? 1 == Nothing fromList [(5, 'a'), (3, 'b')] !? 5 == Just 'a' Since: 0.5.9 (\\) :: Ord k => Map k a -> Map k b -> Map k a infixl 9 Source # Same as difference. # Query null :: Map k a -> Bool Source # O(1). Is the map empty? Data.Map.null (empty) == True Data.Map.null (singleton 1 'a') == False size :: Map k a -> Int Source # O(1). The number of elements in the map. size empty == 0 size (singleton 1 'a') == 1 size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3 member :: Ord k => k -> Map k a -> Bool Source # O(log n). Is the key a member of the map? See also notMember. member 5 (fromList [(5,'a'), (3,'b')]) == True member 1 (fromList [(5,'a'), (3,'b')]) == False notMember :: Ord k => k -> Map k a -> Bool Source # O(log n). Is the key not a member of the map? See also member. notMember 5 (fromList [(5,'a'), (3,'b')]) == False notMember 1 (fromList [(5,'a'), (3,'b')]) == True lookup :: Ord k => k -> Map k a -> Maybe a Source # O(log n). Lookup the value at a key in the map. The function will return the corresponding value as (Just value), or Nothing if the key isn't in the map. An example of using lookup: import Prelude hiding (lookup) import Data.Map employeeDept = fromList([("John","Sales"), ("Bob","IT")]) deptCountry = fromList([("IT","USA"), ("Sales","France")]) countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")]) employeeCurrency :: String -> Maybe String employeeCurrency name = do dept <- lookup name employeeDept country <- lookup dept deptCountry lookup country countryCurrency main = do putStrLn$ "John's currency: " ++ (show (employeeCurrency "John"))
putStrLn $"Pete's currency: " ++ (show (employeeCurrency "Pete")) The output of this program:  John's currency: Just "Euro" Pete's currency: Nothing findWithDefault :: Ord k => a -> k -> Map k a -> a Source # O(log n). The expression (findWithDefault def k map) returns the value at key k or returns default value def when the key is not in the map. findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x' findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a' lookupLT :: Ord k => k -> Map k v -> Maybe (k, v) Source # O(log n). Find largest key smaller than the given one and return the corresponding (key, value) pair. lookupLT 3 (fromList [(3,'a'), (5,'b')]) == Nothing lookupLT 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a') lookupGT :: Ord k => k -> Map k v -> Maybe (k, v) Source # O(log n). Find smallest key greater than the given one and return the corresponding (key, value) pair. lookupGT 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b') lookupGT 5 (fromList [(3,'a'), (5,'b')]) == Nothing lookupLE :: Ord k => k -> Map k v -> Maybe (k, v) Source # O(log n). Find largest key smaller or equal to the given one and return the corresponding (key, value) pair. lookupLE 2 (fromList [(3,'a'), (5,'b')]) == Nothing lookupLE 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a') lookupLE 5 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b') lookupGE :: Ord k => k -> Map k v -> Maybe (k, v) Source # O(log n). Find smallest key greater or equal to the given one and return the corresponding (key, value) pair. lookupGE 3 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a') lookupGE 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b') lookupGE 6 (fromList [(3,'a'), (5,'b')]) == Nothing # Construction empty :: Map k a Source # O(1). The empty map. empty == fromList [] size empty == 0 singleton :: k -> a -> Map k a Source # O(1). A map with a single element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 ## Insertion insert :: Ord k => k -> a -> Map k a -> Map k a Source # O(log n). Insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value. insert is equivalent to insertWith const. insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')] insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')] insert 5 'x' empty == singleton 5 'x' insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a Source # O(log n). Insert with a function, combining new value and old value. insertWith f key value mp will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key, f new_value old_value). insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")] insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] insertWith (++) 5 "xxx" empty == singleton 5 "xxx" insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a Source # O(log n). Insert with a function, combining key, new value and old value. insertWithKey f key value mp will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key,f key new_value old_value). Note that the key passed to f is the same key passed to insertWithKey. let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")] insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] insertWithKey f 5 "xxx" empty == singleton 5 "xxx" insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a, Map k a) Source # O(log n). Combines insert operation with old value retrieval. The expression (insertLookupWithKey f k x map) is a pair where the first element is equal to (lookup k map) and the second element equal to (insertWithKey f k x map). let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")]) insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")]) insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx") This is how to define insertLookup using insertLookupWithKey: let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")]) insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")]) ## Delete/Update delete :: Ord k => k -> Map k a -> Map k a Source # O(log n). Delete a key and its value from the map. When the key is not a member of the map, the original map is returned. delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] delete 5 empty == empty adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a Source # O(log n). Update a value at a specific key with the result of the provided function. When the key is not a member of the map, the original map is returned. adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] adjust ("new " ++) 7 empty == empty adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a Source # O(log n). Adjust a value at a specific key. When the key is not a member of the map, the original map is returned. let f key x = (show key) ++ ":new " ++ x adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] adjustWithKey f 7 empty == empty update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a Source # O(log n). The expression (update f k map) updates the value x at k (if it is in the map). If (f x) is Nothing, the element is deleted. If it is (Just y), the key k is bound to the new value y. let f x = if x == "a" then Just "new a" else Nothing update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a Source # O(log n). The expression (updateWithKey f k map) updates the value x at k (if it is in the map). If (f k x) is Nothing, the element is deleted. If it is (Just y), the key k is bound to the new value y. let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a, Map k a) Source # O(log n). Lookup and update. See also updateWithKey. The function returns changed value, if it is updated. Returns the original key value if the map entry is deleted. let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")]) updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")]) updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a") alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a Source # O(log n). The expression (alter f k map) alters the value x at k, or absence thereof. alter can be used to insert, delete, or update a value in a Map. In short : lookup k (alter f k m) = f (lookup k m). let f _ = Nothing alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" let f _ = Just "c" alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")] alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")] alterF :: (Functor f, Ord k) => (Maybe a -> f (Maybe a)) -> k -> Map k a -> f (Map k a) Source # O(log n). The expression (alterF f k map) alters the value x at k, or absence thereof. alterF can be used to inspect, insert, delete, or update a value in a Map. In short: lookup k <$> alterF f k m = f (lookup k m).

Example:

interactiveAlter :: Int -> Map Int String -> IO (Map Int String)
interactiveAlter k m = alterF f k m where
f Nothing -> do
putStrLn $show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) -> do putStrLn "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserresponse2 :: IO (Maybe String)  alterF is the most general operation for working with an individual key that may or may not be in a given map. When used with trivial functors like Identity and Const, it is often slightly slower than more specialized combinators like lookup and insert. However, when the functor is non-trivial and key comparison is not particularly cheap, it is the fastest way. Note on rewrite rules: This module includes GHC rewrite rules to optimize alterF for the Const and Identity functors. In general, these rules improve performance. The sole exception is that when using Identity, deleting a key that is already absent takes longer than it would without the rules. If you expect this to occur a very large fraction of the time, you might consider using a private copy of the Identity type. Note: alterF is a flipped version of the at combinator from At. Since: 0.5.8 # Combine ## Union union :: Ord k => Map k a -> Map k a -> Map k a Source # O(m*log(n/m + 1)), m <= n. The expression (union t1 t2) takes the left-biased union of t1 and t2. It prefers t1 when duplicate keys are encountered, i.e. (union == unionWith const). union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")] unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a Source # O(m*log(n/m + 1)), m <= n. Union with a combining function. unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")] unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a Source # O(m*log(n/m + 1)), m <= n. Union with a combining function. let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")] unions :: Ord k => [Map k a] -> Map k a Source # The union of a list of maps: (unions == foldl union empty). unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "b"), (5, "a"), (7, "C")] unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])] == fromList [(3, "B3"), (5, "A3"), (7, "C")] unionsWith :: Ord k => (a -> a -> a) -> [Map k a] -> Map k a Source # The union of a list of maps, with a combining operation: (unionsWith f == foldl (unionWith f) empty). unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")] ## Difference difference :: Ord k => Map k a -> Map k b -> Map k a Source # O(m*log(n/m + 1)), m <= n. Difference of two maps. Return elements of the first map not existing in the second map. difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b" differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a Source # O(n+m). Difference with a combining function. When two equal keys are encountered, the combining function is applied to the values of these keys. If it returns Nothing, the element is discarded (proper set difference). If it returns (Just y), the element is updated with a new value y. let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")]) == singleton 3 "b:B" differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a Source # O(n+m). Difference with a combining function. When two equal keys are encountered, the combining function is applied to the key and both values. If it returns Nothing, the element is discarded (proper set difference). If it returns (Just y), the element is updated with a new value y. let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")]) == singleton 3 "3:b|B" ## Intersection intersection :: Ord k => Map k a -> Map k b -> Map k a Source # O(m*log(n/m + 1)), m <= n. Intersection of two maps. Return data in the first map for the keys existing in both maps. (intersection m1 m2 == intersectionWith const m1 m2). intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a" intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c Source # O(m*log(n/m + 1)), m <= n. Intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA" intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c Source # O(m*log(n/m + 1)), m <= n. Intersection with a combining function. let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A" ## General combining functions ## Unsafe general combining function mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c) -> Map k a -> Map k b -> Map k c Source # O(n+m). An unsafe general combining function. WARNING: This function can produce corrupt maps and its results may depend on the internal structures of its inputs. Users should prefer merge or mergeA. When mergeWithKey is given three arguments, it is inlined to the call site. You should therefore use mergeWithKey only to define custom combining functions. For example, you could define unionWithKey, differenceWithKey and intersectionWithKey as myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2 myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2 myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2 When calling mergeWithKey combine only1 only2, a function combining two Maps is created, such that • if a key is present in both maps, it is passed with both corresponding values to the combine function. Depending on the result, the key is either present in the result with specified value, or is left out; • a nonempty subtree present only in the first map is passed to only1 and the output is added to the result; • a nonempty subtree present only in the second map is passed to only2 and the output is added to the result. The only1 and only2 methods must return a map with a subset (possibly empty) of the keys of the given map. The values can be modified arbitrarily. Most common variants of only1 and only2 are id and const empty, but for example map f, filterWithKey f, or mapMaybeWithKey f could be used for any f. # Traversal ## Map map :: (a -> b) -> Map k a -> Map k b Source # O(n). Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")] mapWithKey :: (k -> a -> b) -> Map k a -> Map k b Source # O(n). Map a function over all values in the map. let f key x = (show key) ++ ":" ++ x mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")] traverseWithKey :: Applicative t => (k -> a -> t b) -> Map k a -> t (Map k b) Source # O(n). traverseWithKey f m == fromList$ traverse ((k, v) -> (,) k $f k v) (toList m) That is, behaves exactly like a regular traverse except that the traversing function also has access to the key associated with a value. traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')]) traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing traverseMaybeWithKey :: Applicative f => (k -> a -> f (Maybe b)) -> Map k a -> f (Map k b) Source # O(n). Traverse keys/values and collect the Just results. Since: 0.5.8 mapAccum :: (a -> b -> (a, c)) -> a -> Map k b -> (a, Map k c) Source # O(n). The function mapAccum threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")]) mapAccumWithKey :: (a -> k -> b -> (a, c)) -> a -> Map k b -> (a, Map k c) Source # O(n). The function mapAccumWithKey threads an accumulating argument through the map in ascending order of keys. let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X") mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")]) mapAccumRWithKey :: (a -> k -> b -> (a, c)) -> a -> Map k b -> (a, Map k c) Source # O(n). The function mapAccumR threads an accumulating argument through the map in descending order of keys. mapKeys :: Ord k2 => (k1 -> k2) -> Map k1 a -> Map k2 a Source # O(n*log n). mapKeys f s is the map obtained by applying f to each key of s. The size of the result may be smaller if f maps two or more distinct keys to the same new key. In this case the value at the greatest of the original keys is retained. mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")] mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c" mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c" mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1 -> k2) -> Map k1 a -> Map k2 a Source # O(n*log n). mapKeysWith c f s is the map obtained by applying f to each key of s. The size of the result may be smaller if f maps two or more distinct keys to the same new key. In this case the associated values will be combined using c. The value at the greater of the two original keys is used as the first argument to c. mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab" mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab" mapKeysMonotonic :: (k1 -> k2) -> Map k1 a -> Map k2 a Source # O(n). mapKeysMonotonic f s == mapKeys f s, but works only when f is strictly monotonic. That is, for any values x and y, if x < y then f x < f y. The precondition is not checked. Semi-formally, we have: and [x < y ==> f x < f y | x <- ls, y <- ls] ==> mapKeysMonotonic f s == mapKeys f s where ls = keys s This means that f maps distinct original keys to distinct resulting keys. This function has better performance than mapKeys. mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")] valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True valid (mapKeysMonotonic (\ _ -> 1) (fromList [(5,"a"), (3,"b")])) == False # Folds foldr :: (a -> b -> b) -> b -> Map k a -> b Source # O(n). Fold the values in the map using the given right-associative binary operator, such that foldr f z == foldr f z . elems. For example, elems map = foldr (:) [] map let f a len = len + (length a) foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4 foldl :: (a -> b -> a) -> a -> Map k b -> a Source # O(n). Fold the values in the map using the given left-associative binary operator, such that foldl f z == foldl f z . elems. For example, elems = reverse . foldl (flip (:)) [] let f len a = len + (length a) foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4 foldrWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b Source # O(n). Fold the keys and values in the map using the given right-associative binary operator, such that foldrWithKey f z == foldr (uncurry f) z . toAscList. For example, keys map = foldrWithKey (\k x ks -> k:ks) [] map let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")" foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)" foldlWithKey :: (a -> k -> b -> a) -> a -> Map k b -> a Source # O(n). Fold the keys and values in the map using the given left-associative binary operator, such that foldlWithKey f z == foldl (\z' (kx, x) -> f z' kx x) z . toAscList. For example, keys = reverse . foldlWithKey (\ks k x -> k:ks) [] let f result k a = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")" foldlWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (3:b)(5:a)" foldMapWithKey :: Monoid m => (k -> a -> m) -> Map k a -> m Source # O(n). Fold the keys and values in the map using the given monoid, such that foldMapWithKey f = fold . mapWithKey f This can be an asymptotically faster than foldrWithKey or foldlWithKey for some monoids. Since: 0.5.4 ## Strict folds foldr' :: (a -> b -> b) -> b -> Map k a -> b Source # O(n). A strict version of foldr. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value. foldl' :: (a -> b -> a) -> a -> Map k b -> a Source # O(n). A strict version of foldl. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value. foldrWithKey' :: (k -> a -> b -> b) -> b -> Map k a -> b Source # O(n). A strict version of foldrWithKey. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value. foldlWithKey' :: (a -> k -> b -> a) -> a -> Map k b -> a Source # O(n). A strict version of foldlWithKey. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value. # Conversion elems :: Map k a -> [a] Source # O(n). Return all elements of the map in the ascending order of their keys. Subject to list fusion. elems (fromList [(5,"a"), (3,"b")]) == ["b","a"] elems empty == [] keys :: Map k a -> [k] Source # O(n). Return all keys of the map in ascending order. Subject to list fusion. keys (fromList [(5,"a"), (3,"b")]) == [3,5] keys empty == [] assocs :: Map k a -> [(k, a)] Source # O(n). An alias for toAscList. Return all key/value pairs in the map in ascending key order. Subject to list fusion. assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")] assocs empty == [] keysSet :: Map k a -> Set k Source # O(n). The set of all keys of the map. keysSet (fromList [(5,"a"), (3,"b")]) == Data.Set.fromList [3,5] keysSet empty == Data.Set.empty fromSet :: (k -> a) -> Set k -> Map k a Source # O(n). Build a map from a set of keys and a function which for each key computes its value. fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] fromSet undefined Data.Set.empty == empty ## Lists toList :: Map k a -> [(k, a)] Source # O(n). Convert the map to a list of key/value pairs. Subject to list fusion. toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")] toList empty == [] fromList :: Ord k => [(k, a)] -> Map k a Source # O(n*log n). Build a map from a list of key/value pairs. See also fromAscList. If the list contains more than one value for the same key, the last value for the key is retained. If the keys of the list are ordered, linear-time implementation is used, with the performance equal to fromDistinctAscList. fromList [] == empty fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")] fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")] fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a Source # O(n*log n). Build a map from a list of key/value pairs with a combining function. See also fromAscListWith. fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")] fromListWith (++) [] == empty fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k, a)] -> Map k a Source # O(n*log n). Build a map from a list of key/value pairs with a combining function. See also fromAscListWithKey. let f k a1 a2 = (show k) ++ a1 ++ a2 fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")] fromListWithKey f [] == empty ## Ordered lists toAscList :: Map k a -> [(k, a)] Source # O(n). Convert the map to a list of key/value pairs where the keys are in ascending order. Subject to list fusion. toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")] toDescList :: Map k a -> [(k, a)] Source # O(n). Convert the map to a list of key/value pairs where the keys are in descending order. Subject to list fusion. toDescList (fromList [(5,"a"), (3,"b")]) == [(5,"a"), (3,"b")] fromAscList :: Eq k => [(k, a)] -> Map k a Source # O(n). Build a map from an ascending list in linear time. The precondition (input list is ascending) is not checked. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")] valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False fromAscListWith :: Eq k => (a -> a -> a) -> [(k, a)] -> Map k a Source # O(n). Build a map from an ascending list in linear time with a combining function for equal keys. The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")] valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k, a)] -> Map k a Source # O(n). Build a map from an ascending list in linear time with a combining function for equal keys. The precondition (input list is ascending) is not checked. let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False fromDistinctAscList :: [(k, a)] -> Map k a Source # O(n). Build a map from an ascending list of distinct elements in linear time. The precondition is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False fromDescList :: Eq k => [(k, a)] -> Map k a Source # O(n). Build a map from a descending list in linear time. The precondition (input list is descending) is not checked. fromDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")] fromDescList [(5,"a"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "b")] valid (fromDescList [(5,"a"), (5,"b"), (3,"b")]) == True valid (fromDescList [(5,"a"), (3,"b"), (5,"b")]) == False Since: 0.5.8 fromDescListWith :: Eq k => (a -> a -> a) -> [(k, a)] -> Map k a Source # O(n). Build a map from a descending list in linear time with a combining function for equal keys. The precondition (input list is descending) is not checked. fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "ba")] valid (fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")]) == True valid (fromDescListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False Since: 0.5.8 fromDescListWithKey :: Eq k => (k -> a -> a -> a) -> [(k, a)] -> Map k a Source # O(n). Build a map from a descending list in linear time with a combining function for equal keys. The precondition (input list is descending) is not checked. let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] valid (fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")]) == True valid (fromDescListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False fromDistinctDescList :: [(k, a)] -> Map k a Source # O(n). Build a map from a descending list of distinct elements in linear time. The precondition is not checked. fromDistinctDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")] valid (fromDistinctDescList [(5,"a"), (3,"b")]) == True valid (fromDistinctDescList [(5,"a"), (5,"b"), (3,"b")]) == False Since: 0.5.8 # Filter filter :: (a -> Bool) -> Map k a -> Map k a Source # O(n). Filter all values that satisfy the predicate. filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty filter (< "a") (fromList [(5,"a"), (3,"b")]) == empty filterWithKey :: (k -> a -> Bool) -> Map k a -> Map k a Source # O(n). Filter all keys/values that satisfy the predicate. filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" restrictKeys :: Ord k => Map k a -> Set k -> Map k a Source # O(m*log(n/m + 1)), m <= n. Restrict a Map to only those keys found in a Set. m restrictKeys' s = filterWithKey (k _ -> k member' s) m m restrictKeys' s = m intersect fromSet (const ()) s  Since: 0.5.8 withoutKeys :: Ord k => Map k a -> Set k -> Map k a Source # O(m*log(n/m + 1)), m <= n. Remove all keys in a Set from a Map. m withoutKeys' s = filterWithKey (k _ -> k notMember' s) m m withoutKeys' s = m difference' fromSet (const ()) s  Since: 0.5.8 partition :: (a -> Bool) -> Map k a -> (Map k a, Map k a) Source # O(n). Partition the map according to a predicate. The first map contains all elements that satisfy the predicate, the second all elements that fail the predicate. See also split. partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a") partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty) partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")]) partitionWithKey :: (k -> a -> Bool) -> Map k a -> (Map k a, Map k a) Source # O(n). Partition the map according to a predicate. The first map contains all elements that satisfy the predicate, the second all elements that fail the predicate. See also split. partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b") partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty) partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")]) takeWhileAntitone :: (k -> Bool) -> Map k a -> Map k a Source # O(log n). Take while a predicate on the keys holds. The user is responsible for ensuring that for all keys j and k in the map, j < k ==> p j >= p k. See note at spanAntitone. takeWhileAntitone p = fromDistinctAscList . takeWhile (p . fst) . toList takeWhileAntitone p = filterWithKey (k _ -> p k)  Since: 0.5.8 dropWhileAntitone :: (k -> Bool) -> Map k a -> Map k a Source # O(log n). Drop while a predicate on the keys holds. The user is responsible for ensuring that for all keys j and k in the map, j < k ==> p j >= p k. See note at spanAntitone. dropWhileAntitone p = fromDistinctAscList . dropWhile (p . fst) . toList dropWhileAntitone p = filterWithKey (k -> not (p k))  Since: 0.5.8 spanAntitone :: (k -> Bool) -> Map k a -> (Map k a, Map k a) Source # O(log n). Divide a map at the point where a predicate on the keys stops holding. The user is responsible for ensuring that for all keys j and k in the map, j < k ==> p j >= p k. spanAntitone p xs = (takeWhileAntitone p xs, dropWhileAntitone p xs) spanAntitone p xs = partition p xs  Note: if p is not actually antitone, then spanAntitone will split the map at some unspecified point where the predicate switches from holding to not holding (where the predicate is seen to hold before the first key and to fail after the last key). Since: 0.5.8 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b Source # O(n). Map values and collect the Just results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a" mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b Source # O(n). Map keys/values and collect the Just results. let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3" mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c) Source # O(n). Map values and separate the Left and Right results. let f a = if a < "c" then Left a else Right a mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")]) mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c) Source # O(n). Map keys/values and separate the Left and Right results. let f k a = if k < 5 then Left (k * 2) else Right (a ++ a) mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")]) mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")]) split :: Ord k => k -> Map k a -> (Map k a, Map k a) Source # O(log n). The expression (split k map) is a pair (map1,map2) where the keys in map1 are smaller than k and the keys in map2 larger than k. Any key equal to k is found in neither map1 nor map2. split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")]) split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a") split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a") split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty) split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty) splitLookup :: Ord k => k -> Map k a -> (Map k a, Maybe a, Map k a) Source # O(log n). The expression (splitLookup k map) splits a map just like split but also returns lookup k map. splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")]) splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a") splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a") splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty) splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty) splitRoot :: Map k b -> [Map k b] Source # O(1). Decompose a map into pieces based on the structure of the underlying tree. This function is useful for consuming a map in parallel. No guarantee is made as to the sizes of the pieces; an internal, but deterministic process determines this. However, it is guaranteed that the pieces returned will be in ascending order (all elements in the first submap less than all elements in the second, and so on). Examples: splitRoot (fromList (zip [1..6] ['a'..])) == [fromList [(1,'a'),(2,'b'),(3,'c')],fromList [(4,'d')],fromList [(5,'e'),(6,'f')]] splitRoot empty == [] Note that the current implementation does not return more than three submaps, but you should not depend on this behaviour because it can change in the future without notice. Since: 0.5.4 # Submap isSubmapOf :: (Ord k, Eq a) => Map k a -> Map k a -> Bool Source # O(m*log(n/m + 1)), m <= n. This function is defined as (isSubmapOf = isSubmapOfBy (==)). isSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool Source # O(m*log(n/m + 1)), m <= n. The expression (isSubmapOfBy f t1 t2) returns True if all keys in t1 are in tree t2, and when f returns True when applied to their respective values. For example, the following expressions are all True: isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)]) But the following are all False: isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)]) isProperSubmapOf :: (Ord k, Eq a) => Map k a -> Map k a -> Bool Source # O(m*log(n/m + 1)), m <= n. Is this a proper submap? (ie. a submap but not equal). Defined as (isProperSubmapOf = isProperSubmapOfBy (==)). isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool Source # O(m*log(n/m + 1)), m <= n. Is this a proper submap? (ie. a submap but not equal). The expression (isProperSubmapOfBy f m1 m2) returns True when m1 and m2 are not equal, all keys in m1 are in m2, and when f returns True when applied to their respective values. For example, the following expressions are all True: isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) But the following are all False: isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)]) isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)]) isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) # Indexed lookupIndex :: Ord k => k -> Map k a -> Maybe Int Source # O(log n). Lookup the index of a key, which is its zero-based index in the sequence sorted by keys. The index is a number from 0 up to, but not including, the size of the map. isJust (lookupIndex 2 (fromList [(5,"a"), (3,"b")])) == False fromJust (lookupIndex 3 (fromList [(5,"a"), (3,"b")])) == 0 fromJust (lookupIndex 5 (fromList [(5,"a"), (3,"b")])) == 1 isJust (lookupIndex 6 (fromList [(5,"a"), (3,"b")])) == False findIndex :: Ord k => k -> Map k a -> Int Source # O(log n). Return the index of a key, which is its zero-based index in the sequence sorted by keys. The index is a number from 0 up to, but not including, the size of the map. Calls error when the key is not a member of the map. findIndex 2 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map findIndex 3 (fromList [(5,"a"), (3,"b")]) == 0 findIndex 5 (fromList [(5,"a"), (3,"b")]) == 1 findIndex 6 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map elemAt :: Int -> Map k a -> (k, a) Source # O(log n). Retrieve an element by its index, i.e. by its zero-based index in the sequence sorted by keys. If the index is out of range (less than zero, greater or equal to size of the map), error is called. elemAt 0 (fromList [(5,"a"), (3,"b")]) == (3,"b") elemAt 1 (fromList [(5,"a"), (3,"b")]) == (5, "a") elemAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a Source # O(log n). Update the element at index, i.e. by its zero-based index in the sequence sorted by keys. If the index is out of range (less than zero, greater or equal to size of the map), error is called. updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")] updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")] updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range deleteAt :: Int -> Map k a -> Map k a Source # O(log n). Delete the element at index, i.e. by its zero-based index in the sequence sorted by keys. If the index is out of range (less than zero, greater or equal to size of the map), error is called. deleteAt 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" deleteAt 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" deleteAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range deleteAt (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range take :: Int -> Map k a -> Map k a Source # Take a given number of entries in key order, beginning with the smallest keys. take n = fromDistinctAscList . take n . toAscList  Since: 0.5.8 drop :: Int -> Map k a -> Map k a Source # Drop a given number of entries in key order, beginning with the smallest keys. drop n = fromDistinctAscList . drop n . toAscList  Since: 0.5.8 splitAt :: Int -> Map k a -> (Map k a, Map k a) Source # O(log n). Split a map at a particular index. splitAt !n !xs = (take n xs, drop n xs)  Since: 0.5.8 # Min/Max lookupMin :: Map k a -> Maybe (k, a) Source # O(log n). The minimal key of the map. Returns Nothing if the map is empty. lookupMin (fromList [(5,"a"), (3,"b")]) == Just (3,"b") findMin empty = Nothing Since: 0.5.9 lookupMax :: Map k a -> Maybe (k, a) Source # O(log n). The maximal key of the map. Returns Nothing if the map is empty. lookupMax (fromList [(5,"a"), (3,"b")]) == Just (5,"a") lookupMax empty = Nothing Since: 0.5.9 findMin :: Map k a -> (k, a) Source # O(log n). The minimal key of the map. Calls error if the map is empty. findMin (fromList [(5,"a"), (3,"b")]) == (3,"b") findMin empty Error: empty map has no minimal element findMax :: Map k a -> (k, a) Source # deleteMin :: Map k a -> Map k a Source # O(log n). Delete the minimal key. Returns an empty map if the map is empty. deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")] deleteMin empty == empty deleteMax :: Map k a -> Map k a Source # O(log n). Delete the maximal key. Returns an empty map if the map is empty. deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")] deleteMax empty == empty deleteFindMin :: Map k a -> ((k, a), Map k a) Source # O(log n). Delete and find the minimal element. deleteFindMin (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((3,"b"), fromList[(5,"a"), (10,"c")]) deleteFindMin Error: can not return the minimal element of an empty map deleteFindMax :: Map k a -> ((k, a), Map k a) Source # O(log n). Delete and find the maximal element. deleteFindMax (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((10,"c"), fromList [(3,"b"), (5,"a")]) deleteFindMax empty Error: can not return the maximal element of an empty map updateMin :: (a -> Maybe a) -> Map k a -> Map k a Source # O(log n). Update the value at the minimal key. updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")] updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateMax :: (a -> Maybe a) -> Map k a -> Map k a Source # O(log n). Update the value at the maximal key. updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")] updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a Source # O(log n). Update the value at the minimal key. updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")] updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a Source # O(log n). Update the value at the maximal key. updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")] updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" minView :: Map k a -> Maybe (a, Map k a) Source # O(log n). Retrieves the value associated with minimal key of the map, and the map stripped of that element, or Nothing if passed an empty map. minView (fromList [(5,"a"), (3,"b")]) == Just ("b", singleton 5 "a") minView empty == Nothing maxView :: Map k a -> Maybe (a, Map k a) Source # O(log n). Retrieves the value associated with maximal key of the map, and the map stripped of that element, or Nothing if passed an empty map. maxView (fromList [(5,"a"), (3,"b")]) == Just ("a", singleton 3 "b") maxView empty == Nothing minViewWithKey :: Map k a -> Maybe ((k, a), Map k a) Source # O(log n). Retrieves the minimal (key,value) pair of the map, and the map stripped of that element, or Nothing if passed an empty map. minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a") minViewWithKey empty == Nothing maxViewWithKey :: Map k a -> Maybe ((k, a), Map k a) Source # O(log n). Retrieves the maximal (key,value) pair of the map, and the map stripped of that element, or Nothing if passed an empty map. maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b") maxViewWithKey empty == Nothing # Debugging showTree :: (Show k, Show a) => Map k a -> String Source # Deprecated: showTree is now in Data.Map.Internal.Debug O(n). Show the tree that implements the map. The tree is shown in a compressed, hanging format. See showTreeWith. showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String Source # Deprecated: showTreeWith is now in Data.Map.Internal.Debug O(n). The expression (showTreeWith showelem hang wide map) shows the tree that implements the map. Elements are shown using the showElem function. If hang is True, a hanging tree is shown otherwise a rotated tree is shown. If wide is True, an extra wide version is shown.  Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]] Map> putStrLn$ showTreeWith (\k x -> show (k,x)) True False t
(4,())
+--(2,())
|  +--(1,())
|  +--(3,())
+--(5,())

Map> putStrLn $showTreeWith (\k x -> show (k,x)) True True t (4,()) | +--(2,()) | | | +--(1,()) | | | +--(3,()) | +--(5,()) Map> putStrLn$ showTreeWith (\k x -> show (k,x)) False True t
+--(5,())
|
(4,())
|
|  +--(3,())
|  |
+--(2,())
|
+--(1,())

valid :: Ord k => Map k a -> Bool Source #

O(n). Test if the internal map structure is valid.

valid (fromAscList [(3,"b"), (5,"a")]) == True
valid (fromAscList [(5,"a"), (3,"b")]) == False


text:
Studies on frequency distributions of ambient temperature available in the literature are limited and are developed assuming that the distributions are symmetric about its average value. The present article examines the suitability of a new parameter, $T¯aˆ$, and a variable, $Taˆ$ to depict generalized distributions. $T¯aˆ$ is a normalized monthly average daily ambient temperature, while $Taˆ$ is a normalized daily ambient temperature. They comprise maximum and minimum ambient temperatures (Ta,max and Ta,min), in addition to monthly average daily ambient temperature, a, and daily ambient temperature, Ta. Correlations have been developed to predict Ta,max and Ta,min needed, in the absence of data. The distributions, developed in terms of $Taˆ$ and $T¯aˆ$ have been suitably represented and tested over 269 locations, latitudes ranging from 8°N to 64°N. The daily ambient temperature values have been predicted within a %rms difference and standard deviations of 0.43% (when Ta’s are in K) and 1.19 K with the expressions developed in the present study.

1.
Aerological Data of India, Part III, Radiation Data, (1971–78), Meteorological Department, New Delhi, India.
2.
Liu
B. Y. H.
, and
Jordan
R. C.
,
1963
, “
A Rational Procedure for Predicting the Long Term Performance of Flat-Plate Solar Energy Collectors
,”
Solar Energy
, Vol.
7
, pp.
53
74
.
3.
Erbs
D. G.
,
Klein
S. A.
, and
Beckman
W. A.
,
1983
, “
Estimation of Degree-Days and Ambient Temperature Bin Data from Monthly Average Temperatures
,”
ASHRAE Journal
, Vol.
25
, pp.
60
65
.
4.
Knight
K. M.
,
Klein
S. A.
, and
Duffie
J. A.
,
1991
, “
A Methodology for the Synthesis of Hourly Weather Data
,”
Solar Energy
, Vol.
46
, pp.
109
120
.
5.
William, M., and Urban, K., 1996, User’s Manual for TMY2S, National Renewable Energy Laboratory, Golden, CO, USA. Also can be accessed at http://rredc.nrel.gov.solar/old_data/nsrdh/tmy2/
This content is only available via PDF.


text:
ROUGH DRAFT authorea.com/94168

# Aims

The Hall Effect is an important part of finding out about charge transport in a material.In this experiment, we aim to determine the charge density in Ge n-type, Ge p-type semiconductor samples, and in a Ag (silver) sample. We will also be determining the transition temperature ($$Tc$$) of the high-Tc superconductor $$Bi_2 Sr_2 Ca_2 Cu_3 O_{10}$$ (aka $$Bi2223$$).

# Introduction

Hall Effect was discovered by Edwin Herbert Hall, an American physicists, in 1879. This phenomenon can be used to determine the sign of the charge carrier in electrical conductors such as semiconductors and superconductors. The fundamental idea of Hall Effect can be illustrated in Figure \ref{fig:HallIllustration}:

\label{fig:HallIllustration} Hall Effect Illustration: The magnetic field is pointing into the page. By convention, the direction of current is defined as the direction of the moving positive charge. Therefore, $$\vec{v}$$ is opposite for positive and negative charge carriers for a $$\vec{I}$$. And according to right hand rule, the magnetic force $$F_M$$ (Equation \ref{eq:righthand}) will be upward for both cases. As charges accumulate at one side of the plate, an electric field $$E$$ is created between the sides. The electric force $$F_E$$ on the current is opposite to $$F_M$$. The Hall voltage is the voltage across the plate when the current does not curve up or down anymore, when $$F_M=F_E$$.


text:
Tuesday, January 21, 2014

Recently I read another blog commenting on the number of spells in Advanced Dungeons & Dragons. This made me think of the AD&D Wizard's Spell Compendium published in the late 90's. I went searching for the number of spells contained in these volumes and discovered -- apparently no one had ever counted them. Not on the covers of the books themselves, not anywhere inside, not anywhere on the Internet that I could find. So I'll be doing that, at the end of this post.

I think it's a very nice collection in 4 volumes, and it easily passes my usual threshold of "did anyone give a shit?". Credits run like this (with lots and lots of acknowledgements and thanks to prior creators and such):
Compilation: Mark Middleton. Development and Editing: Jon Pickens. Additional Development: Richard Baker. Creative Director/Project Coordination: Steve Winter, Thomas Reid. Interior Black and White Art: Glen Michael Angus, Arnie Swekel, Ken Frank, Toren Atkinson, John Snyder.

Notice that while 2nd Edition AD&D came out in the prior decade, these volumes are not listed as 2nd Edition -- just "Advanced Dungeons & Dragons". The project here was to compile all the spells from the entire publication history of AD&D up to that point: as the introduction establishes, "This book is the first in a series that will cover the spells of the AD&D game system from 1975 to 1995" (Vol-1, p. 4), that is: 20 years of publications. The creators here attempted to trawl through every book, module, supplement, Dragon, Dungeon, Polyhedron, and Imagine magazine for wizard spells, updating and polishing as necessary, and put them all in this one reference work. Older spells were formatted in the 2nd Ed. style of the time (somewhat stripped-down headers, range in yards not scale inches, etc.). Forward-and-back references to alternate spell names, reversible spell names, etc., are included throughout. Sidebar notes on historical information and optional usage are given. At the end, an over 100-page set of Appendices is included with lists of different spell categories, specialty lists, errata, and so forth.

This is the kind of work which is not tremendously sexy or "wahoo" but obviously took lots and lots of time and attention -- it took over 3 years from start to finish for the four volumes to be published. I feel like it's the kind of work that I'm attracted to in my own blog writings and elsewhere. Even the 17-page Introduction is a delight to read: well-written and clear-headed about what the project is and what the history of the work has been and why. It gives specific references to works by Jack Vance that one should read to understand the flavor of the AD&D spell system -- scoring extra points for being one of the few places that think to observe that the Vancian creation was a "mathematically-based magic system" (p. 3; emphasis mine). The work clearly follows in the footsteps of the earlier Encyclopedia Magica by Dale "slade" Henson, which compiled the entire history of AD&D magic items in a similar 4-volume set (1994-1995), and established the tradition of various "Compendiums" late in the publishing cycle of editions that came afterward.

Copious new artwork was produced here (about one piece every 3rd page or so) -- while many artists are credited throughout the volumes, it's mostly by Glen Michael Angus and Arnie Swekel (the others above are pretty much just credited in Vol-2). The art has an edgy, lively, active style with a lot of clever situations, reactions, and perspectives -- very old-school, and almost always directly related to one of the unique spells on that page (not just generic "wizard stuff"). The 1st volume cover has a different design than the rest, similar to the prior Encyclopedia Magica (no highlighted logo, no ad copy on the back; top left in the image above) -- in fact, I just this second realized that the white "crease markings" on Vol-1 are part of the art design; for years I thought they were real creases on my copy, until the image googled above showed the exact same markings! The cover is so well done it might be too well done, and it evolved back to a more marketable standard in later volumes.

As noted above, the work tries to incorporate pretty much everything from every source in the first 20 years of the game. Spells from all of the different world settings are included (and annotated symbolically, and indexed at the end), even though some or many of those would be of limited usage in a standard D&D campaign. Original D&D spells were technically left out, although to the extent that they migrated to AD&D, they have versions included. Variant magic systems were not included, such as Forgotten Realms spellfire, Birthright realm-spells, Viking rune-magic etc. Some spells were considered unworkable or obsolete, but even these get short descriptions and references as to "lost magic".

Do I use this compilation in my own games? Well, no, I don't. Partly this is due to my use of the earlier and simpler Original D&D system, and liking a limited number of very short spells that I can have more-or-less memorized and not need to look up during play (see also: my open-gaming product Book of Spells). The other issue is that I've only had the chance to run convention-style one-off games for a number years. But if I had a wide-open campaign I'd like to think that this product would give a fairly deep encyclopedia of spell resources for specialist wizard cabals, NPC magic-users, lost treasure troves, and the like. It's a very nice set.

Okay, so here's where I went through and tried to count up all the spells as best I could. I counted only full spell descriptions in the main body of the books (not the references, reversed spell names, lost magic, or anything like that). Each of the volumes has a note as to its "First Printing" date on the inside cover, and the page numbering runs sequentially through all the volumes (kind of like an academic journal) for a full 1,152 pages.
• Volume 1: A to D, October 1996 -- 576 spells.
• Volume 2: E to Mn, September 1997 -- 597 spells.
• Volume 3: Mo to Sp, February 1998 -- 607 spells.
• Volume 4: Sq to Z, September 1998 -- 393 spells.

The last volume has a smaller number of general spells, because it ends halfway through to make room for the 100+ pages of Appendices. This includes things like the 1st Edition Cantrips (83 cantrip spells), "Dragon King" 10th-level psionic enchantments (28 of those spells), notes on Chronomancy, achieving Lichdom, Paths of Power, and spell lists by frequency, schools of philosophy, effect, thaumaturgy, world setting, specialty, and race. (Cantrips and Dragon King spells are not included in the total count below.) The last page includes errata notes of minor glitches in Vol 1-3 (generally world-specific icons that could be added), and one spell that was accidentally left out of Vol-2 ("Emirikol's Question").

Grand Total: 2,174 Wizard Spells.

If you're interested in using it, you can use the following affiliate link to get all volumes 1-4 volumes of the AD&D Wizard's Spell Compendium (and help support the Wandering DMs channel at the same time):

1. These and the Encyclopedia Magica are fantastic books.

2. While I loved these books for putting everything into one place, you need to be careful with allowing everything in these books into your games. Some of the spells are just ridiculous.

1. Certainly I agree, especially the more world-specific ones. The DM has to be at least a little mindful when placing them, or be willing to retract or modify them later. But I do think think the editors did some pretty reasonable work in that direction already.

3. Great post Delta!

4. I keep waiting to see these turn up at the used bookstores or FLGS because that's a lot spell chaff to stuff into random scrolls, and some of those spells really are ridiculous if what I've culled from old issues of Dragon is any indication.

1. Like a lot of my collection, I got mine off EBay a few years ago. As I write this there's a copy of Vol-1 on EBay for $13 with no bids and 1 day left. Shrink-wrapped copies of the other volumes are listed for$35-60, not the kind of stuff I'd buy (as I expect to actually use anything I get at some point).

5. WotC has apparently released new scans of the pdfs for Encyclopedia Magica series, so perhaps they'll get to releasing new scans of the Compendiums as well.

1. I hope so! It would be a great resource to have in low-cost digital form these days.

2. you can dl a scanned pdf here of all of them
http://archmagev.com/2nd_Ed/

3. Thank you!

6. Excellent post, and thanks for the count! I use these for my 1st edition games, though I strictly enforce material components. Anyway, great job.

1. Thanks! Glad to hear they do work well for your 1st Edition games and that the total count is helpful. I was really surprised when I couldn't find a number from my initial search.

7. A few updates 3 years later. I notice at this time that the first 2 of the 4 volumes are now (again?) available on RPGNow.com (etc.), with "File Last Updated" dates of May 14 and May 21, 2017, respectively. Hopefully the other volumes will be made available shortly.

A spreadsheet index of all the spells is available from James Rizza on Dragonsfoot. His counting there (different from mine) indicates 3,442 spells total!

1. Looking at the list more closely, I think that James duplicated any spell with multiple "schools" of magic listed (so they'd appear separately when sorted, I suppose). Some of us might consider de-duplicating the list for other uses. Also I wish the list included campaign-world-specific identifiers, but that's not here. Nonetheless, a very impressive chunk of work.


text:
• No products in the cart.

# 103.2.1 Data Handling In R

##### Data Analysing is a skill !!

Data Analysing is a skill

It is not like, all the data were available already in the form we require them. It is the duty of the data analyst to take the data, and sometimes he needs to prepare the data by himself, identifying the missing values and replacing them, transpose the data, transform the variables and many other operations on the data. So data handling is a very important part in R. Data Handling  involves all kinds of processes like import, curate, validation and exploration of data. Hence, before moving on to Analysis of data, it is very important for one to be good with data handling.

The data can be stored in different formats, like CSV (Comma Separated Variable), Excel, SQL (database), and many other ways. Various statistical tools are available which are used for the critical analysis of the data. R is highly flexible and open source software which is integrated with all the formats of data storage due to which data handling becomes easy in R.

Here we are going to discuss various data handling which includes

• Data importing from files
• Database server connections
• Working with datasets
• Manipulating the datasets in R
• Creating new variables in R
• Sorting in R & Removing Duplicates
• Exporting the R datasets into external files
• Data Merging, etc.

#### Importing Data from CSV file

CSV (Comma Separated Variable) extension is one of the most commonly used data type. R is compatible with CSV format. By calling a simple function, csv (), we can easily import the data into R.

While defining the path of the CSV file in the csv() function, we must either use “/” or “\\” in the path. The windows style of giving path in which we use a single “\”, doesn’t work in R.

To understand how read.csv() function works, let’s consider a sample program to read the Sales related data from Sales_data.csv as shown below. The function read.csv() imports the data from the CSV file (the path for which is mentioned in the syntax) to R.

In the syntax below, we need to give the local path of the data set as an input to read.csv() function and replace all ‘\’ with ‘\\’.

> Sales <- read.csv("C:\\Users\\venk\\Google Drive\\Training\\Datasets\\Superstore Sales  Data\\Sales_sample.csv")
> Sales
> Sales1

 ##    custId           custName                  custCountry productSold
## 1   23262       Candice Levy                        Congo     SUPA101
## 2   23263       Xerxes Smith                       Panama     DETA200
## 3   23264       Levi Douglas Tanzania, United Republic of     DETA800
## 4   23265       Uriel Benton                 South Africa     SUPA104
## 5   23266       Celeste Pugh                        Gabon     PURA200
## 6   23267       Vance Campos         Syrian Arab Republic     PURA100
## 7   23268       Latifah Wall                   Guadeloupe     DETA100
## 8   23269     Jane Hernandez                    Macedonia     PURA100
## 9   23270        Wanda Garza                   Kyrgyzstan     SUPA103
## 10  23271 Athena Fitzpatrick                      Reunion     SUPA103
## 11  23272      Anjolie Hicks     Turks and Caicos Islands     DETA200
##    salesChannel unitsSold  dateSold
## 1        Retail       117  8/9/2012
## 2        Online        73  7/6/2012
## 3        Online       205 8/18/2012
## 4        Online        14  8/5/2012
## 5        Retail       170 8/11/2012
## 6        Retail       129 7/11/2012
## 7        Retail        82 7/12/2012
## 8        Retail       116  6/3/2012
## 9        Online        67  6/7/2012
## 10       Retail       125 7/27/2012
## 11       Retail        71 7/31/2012

#### Importing from SAS files

We have earlier discussed about installing packages. In order to import data from SAS files, we need to install the package “sas7bdat”.

SAS, also known as the Statistical Analysis Software, is used to perform the functions of Data Analytics. SAS is a highly specialized tool in analytics. R is compatible with the SAS and the JMV format. There is an external library available which needs to be installed before importing the data of SAS format.

To install the package, use the command packages(sas7bdat) and to use that package, we need to call the library(sas7bdat). After installing, it will automatically load the library into the R directory. Once the library is installed, users can import the data by calling the function sas7bdat(). Giving path for this function is same as we did for the csv file format.

A sample program to import the SAS data into R is shown below:

> library(sas7bdat)
> View(gnpdata)

 ## Warning: package 'sas7bdat' was built under R version 3.2.3
##   DATE   GNP CONSUMP INVEST EXPORTS  GOVT
## 1    0 516.1   325.5   88.7     4.3  97.6
## 2   91 514.5   331.6   78.1     5.1  99.6
## 3  182 517.7   331.7   77.4     6.5 102.1
## 4  274 513.0   333.8   68.5     7.7 103.0
## 5  366 517.4   334.4   69.5     8.3 105.3
## 6  456 527.9   339.1   74.7     7.0 107.1

#### Data import from Excel files

Excel is one of the most widely used tools for reporting and ad-hoc data analysis. The excel files contain mostly aggregated and even raw data sometimes. The function, xlsx() is used to import the desired excel file into R. The spreadsheet is read through this function and is stored into a data frame. Here’s an example of how to read the data from excel into R.

> library(xlsx)
> wb_data <- read.xlsx("C:\\Users\\venk\\Google Drive\\Training\\Datasets\\World Bank Data\\World Bank Indicators.xlsx" , sheetName="Data by country")

There’s another way through which data can be imported into R. There is a function called loadWorkbook() from the XLConnect package, which can be used to read the complete workbook. To import any such worksheet, the function readWorksheet() is called. Java package needs to be installed before using XLConnect.

> library(XLConnect)
> wb_data <- readWorksheet(loadWorkbook("C:\\Users\\venk\\Google Drive\\Training\\Datasets\\World Bank Data\\World Bank Indicators.xlsx" ),sheet=1)

We may have some Java related issues while importing Excel files. Excel is not just a flat file like CSV. The excel file contains lots of other information such as indexes, apart from just data. If we find errors even after installing the necessary packages, then we must first store the excel data in CSV format and then import it.

In the next post you will be learning about Database server connections.

20th June 2017

### 0 responses on "103.2.1 Data Handling In R"

Statinfer Software Solutions LLP

Software Technology Parks of India,
NH16, Krishna Nagar, Benz Circle,


text:
## Fair-rite’s ‘new’ #43 permeability data

Fair-rite publishes spreadsheets of the complex permeability characteristic of many of the ferrite mixes. This note is about #43 mix and clarification I sought from Fair-rite.

### Question

I note that recently, the published table of #43 permeability changed subtly but significantly. Does this table apply to historical product, or does it only apply to new product, ie was there an actual change in the mix, or what it the result of better measurement of characteristics?

## Surely there cannot be more forward power than the transmitter makes?

Let’s explore a simple numerical example of a practical line operating in Transverse Electro Magnetic (TEM) mode (the usual thing for practical coax lines at HF).

## Let’s review the meaning of 50Ω line.

It means that the line geometry imposes a natural constraint on a wave travelling in the line that V/I=50… but remember that TEM waves are free to travel in (only) two directions. This natural ratio of V/I is called the characteristic impedance Zo. Continue reading Surely there cannot be more forward power than the transmitter makes?

## Select a ferrite core material and sufficient primary turns for a low InsertionVSWR 50Ω broadband RF transformer – nanoVNA – loss components graph

Select a ferrite core material and sufficient primary turns for a low InsertionVSWR 50Ω broadband RF transformer – nanoVNA gave an explanation of how to use a nanoVNA or the like to select a suitable core and sufficient turns for a low InsertionVSWR broad band 50Ω transformer. Continue reading Select a ferrite core material and sufficient primary turns for a low InsertionVSWR 50Ω broadband RF transformer – nanoVNA – loss components graph

## The devil is in the detail…

An image from one of my articles has been posted online in some discussions, with attribution of the underlying image, but it includes some changes / annotations.

I think that this is a better image.

The difference is in the two pin assembly at lower centre, an addition to my original image. My recommendation is that the DUT is attached to the same side of the pin strip as was used for the calibration parts, as shown. Though I did not intend that this jig be used much above 100MHz, small details like this might improve its accuracy. Continue reading The devil is in the detail…