Pattern Match Failure in List in Haskell - list

I have one problem with pattern matching. When I give input to (x:y:ys) the list containing 3 elements, hugs complain that there is: pattern match failure.
I guess that the problem is here
takeNearestOnes agent (y:ys) (x:nearestOnes)
because it fails to match three elements with list containing two elements
This is full code:
takeNearestOnes agent (x:y:ys) nearestOnes
| first == second = takeNearestOnes agent (y:ys) (x:nearestOnes)
| otherwise = (x:nearestOnes)
where first=(manhattanDistance x (agentCoord agent))
second=(manhattanDistance y (agentCoord agent)
How can I overcome this? Thanks in advance

Since your function is recursive and decreasing the list, you could eventually going to work you're way down to a list of 1 element, in which case your match will fail. You can fix this by adding another case of your function which handles it however you feel is appropriate
Something like
takeNearestOnes agent [x] nearestOnes = doSomething
takeNearestOnes agent [] nearestOnes = doSomethingElse

What should be the result of takeNearestOnes agent [x] nearestOnes? What should be the result of takeNearestOnes agent [] nearestOnes?
Write extra equations for these cases.

Related

f# - simple iterate on list of pairs

I need to go through a list of pairs and check for one of the values in the pair. Say I got this list:
let listOfPairs = [("Joe",100);("Bo",5);("Morten",60)]
And I have to check whether the int value of the pair is equal to 100 or not. I'm not looking for the List.exist method but rather some way to check this with pattern matching, going through every pair in the list and check if the value is 100 or not.
I've obviously tried a lot thing myself but it's too bad to have any good influence in this post. Any ideas or suggestions are very appreciated, thanks in advance.
If you don't want to use List.exist then you could write a recursive function that pattern matches to extract the value:
let rec listContainsHundred = function
| (_, 100)::_ -> true
| _::tail -> listContainsHundred tail
| [] -> false
Otherwise a simple solution with List.exists would be:
List.exists (snd >> ((=) 100)) listOfPairs

Appending lists in SML

I'm trying to add an int list list with another int list list using the append function, but I can't get it to work the way I want.
Say that I want to append [[1,2,3,4,5]] with [6,7] so that I get [[1,2,3,4,5,6,7]].
Here's my attempt: [1,2,3,4,5]::[]#[6,7]::[], but it just gives me the list I want to append as a list of its own instead of the two lists combined into one, like this: [[1,2,3,4,5],[6,7]].
How can I re-write the operation to make it return [[1,2,3,4,5,6,7]]?
Your question is too unspecific. You are dealing with nested lists. Do you want to append the second list to every inner list of the nested list, or only the first one? Your example doesn't tell.
For the former:
fun appendAll xss ys = List.map (fn xs => xs # ys) xss
For the latter:
fun appendHd [] ys = raise Empty
| appendHd (xs::xss) ys = (xs # ys)::xss
However, both of these should rarely be needed, and I somehow feel that you are trying to solve the wrong problem if you end up there.

instance Alternative ZipList in Haskell?

ZipList comes with a Functor and an Applicative instance (Control.Applicative) but why not Alternative?
Is there no good instance?
What about the one proposed below?
Is it flawed?
is it useless?
Are there other reasonable possibilities (like Bool can be a monoid in two ways) and therefore neither should be the instance?
I searched for "instance Alternative ZipList" (with the quotes to find code first) and only found the library, some tutorials, lecture notes yet no actual instance.
Matt Fenwick said ZipList A will only be a monoid if A is (see here). Lists are monoids though, regardless of the element type.
This other answer by AndrewC to the same question discusses how an Alternative instance might look like. He says
There are two sensible choices for Zip [1,3,4] <|> Zip [10,20,30,40]:
Zip [1,3,4] because it's first - consistent with Maybe
Zip [10,20,30,40] because it's longest - consistent with Zip [] being discarded
where Zip is basically ZipList.
I think the answer should be Zip [1,3,4,40]. Let's see the instance:
instance Aternative Zip where
empty = Zip []
Zip xs <|> Zip ys = Zip (go xs ys) where
go [] ys = ys
go (x:xs) ys = x : go xs (drop 1 ys)
The only Zip a we can produce without knowing the type argument a is Zip [] :: Zip a, so there is little choice for empty. If the empty list is the neutral element of the monoid, we might be tempted to use list concatenation. However, go is not (++) because of the drop 1. Every time we use one entry of the first argument list, we drop one off the second as well. Thus we have a kind of overlay: The left argument list hides the beginning of the right one (or all of it).
[ 1, 3, 4,40] [10,20,30,40] [ 1, 3, 4] [ 1, 3, 4]
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | | | | | |
[ 1, 3, 4] | [10,20,30,40] []| | | [ 1, 3, 4]
[10,20,30,40] [ 1, 3, 4] [ 1, 3, 4] []
One intuition behind ziplists is processes: A finite or infinite stream of results. When zipping, we combine streams, which is reflected by the Applicative instance. When the end of the list is reached, the stream doesn't produce further elements. This is where the Alternative instance comes in handy: we can name a concurrent replacement (alternative, really), taking over as soon as the default process terminates.
For example we could write fmap Just foo <|> pure Nothing to wrap every element of the ziplist foo into a Just and continue with Nothing afterwards. The resulting ziplist is infinite, reverting to a default value after all (real) values have been used up. This could of course be done by hand, by appending an infinite list inside the Zip constructor. Yet the above is more elegant and does not assume knowledge of constructors, leading to higher code reusability.
We don't need any assumption on the element type (like being a monoid itself). At the same time the definition is not trivial (as (<|>) = const would be). It makes use of the list structure by pattern matching on the first argument.
The definition of <|> given above is associative and the empty list really is the empty element. We have
Zip [] <*> xs == fs <*> Zip [] == Zip [] -- 0*x = x*0 = 0
Zip [] <|> xs == xs <|> Zip [] == xs -- 0+x = x+0 = x
(fs <|> gs) <*> xs == fs <*> xs <|> gs <*> xs
fs <*> (xs <|> ys) == fs <*> xs <|> fs <*> ys
so all the laws you could ask for are satisfied (which is not true for list concatenation).
This instance is consistent with the one for Maybe: choice is biased to the left, yet when the left argument is unable to produce a value, the right argument takes over. The functions
zipToMaybe :: Zip a -> Maybe a
zipToMaybe (Zip []) = Nothing
zipToMaybe (Zip (x:_)) = Just x
maybeToZip :: Maybe a -> Zip a
maybeToZip Nothing = Zip []
maybeToZip (Just x) = Zip (repeat x)
are morphisms of alternatives (meaning psi x <|> psi y = psi (x <|> y) and psi x <*> psi y = psi (x <*> y)).
Edit: For the some/many methods I'd guess
some (Zip z) = Zip (map repeat z)
many (Zip z) = Zip (map repeat z ++ repeat [])
Tags / Indeces
Interesting. A not completely unrelated thought: ZipLists can be seen as ordinary lists with elements tagged by their (increasing) position index in the list. Zipping application joins two lists by pairing equally-indexed elements.
Imagine lists with elements tagged by (non-decreasing) Ord values. Zippery application would pair-up equally-tagged elements, throwing away all mismatches (it has its uses); zippery alternative could perform order-preserving left-preferring union on tag values (alternative on regular lists is also kind of a union).
This fully agrees with what you propose for indexed lists (aka ZipLists).
So yes, it makes sense.
Streams
One interpretation of a list of values is non-determinacy, which is consistent with the monad instance for lists, but ZipLists can be interpreted as synchronous streams of values which are combined in sequence.
With this stream interpretation it's you don't think in terms of the whole list, so choosing the longest stream is clearly cheating, and the correct interpretation of failing over from the first ZipList to the second in the definition <|> would be to do so on the fly as the first finishes, as you say in your instance.
Zipping two lists together doesn't do this simply because of the type signature, but it's the correct interpretation of <|>.
Longest Possible List
When you zip two lists together, the result is the minimum of the two lengths. This is because that's the longest possible list that meets the type signature without using ⊥. It's a mistake to think of this as picking the shorter of the two lengths - it's the longest possible.
Similarly <|> should generate the longest possible list, and it should prefer the left list. Clearly it should take the whole of the left list and take up the right list where the left left off to preserve synchronisation/zippiness.
Your instance is OK, but it does something ZipList doesn't by
(a) aiming for the longest list, and
(b) mixing elements between source lists.
Zipping as an operation stops at the length of the shortest list.
That's why I concluded in my answer:
Thus the only sensible Alternative instance is:
instance Alternative Zip where
empty = Zip []
Zip [] <|> x = x
Zip xs <|> _ = Zip xs
This is consistent with the Alternative instances for Maybe and parsers that say you should do a if it doesn't fail and go with b if it does. You can say a shorter list is less successful than a longer one, but I don't think you can say a non-empty list is a complete fail.
empty = Zip [] is chosen because it has to be polymorphic in the element type of the list, and the only such list is []
For balance, I don't think your instance is terrible, I think this is cleaner, but hey ho, roll your own as you need it!
There is in fact a sensible Alternative instance for ZipList. It comes from a paper on free near-semirings (which MonadPlus and Alternative are examples of):
instance Alternative ZipList where
empty = ZipList []
ZipList xs <|> ZipList ys = ZipList $ go xs ys where
go [] bs = bs
go as [] = as
go (a:as) (_:bs) = a:go as bs
This is a more performant version of the original code for it, which was
ZipList xs <|> ZipList ys = ZipList $ xs ++ drop (length xs) ys
My guiding intuition for Alternative comes from parsers which suggest that if one branch of your alternative fails somehow it should be eradicated thus leading to a Longest-style Alternative that probably isn't terrifically useful. This would be unbiased (unlike parsers) but fail on infinite lists.
Then again, all they must do, as you suggest, is form a Monoid. Yours is left biased in a way that ZipList doesn't usually embody, though—you could clearly form the reflected version of your Alternative instance just as easily. As you point out, this is the convention with Maybe as well, but I'm not sure there's any reason for ZipList to follow that convention.
There's no sensible some or many I don't believe, although few Alternatives actually have those—perhaps they'd have been better isolated into a subclass of Alternative.
Frankly, I don't think your suggestion is a bad instance to have, but I don't have any confidence about it being "the" alternative instance implied by having a ZipList. Perhaps it'd be best to see where else this kind of "extension" instance could apply (trees?) and write it as a library.

Removing the first instance of x from a list

I am new to Haskell and have been trying to pick up the basics.
Assume I have the following list y:
3:3:2:1:9:7:3:[]
I am trying to find a way to delete the first occurrence of 3 in list y. Is this possible using simple list comprehension?
What I tried (this method deletes all instances from a list):
deleteFirst _ [] = []
deleteFirst a (b:bc) | a == b = deleteFirst a bc
| otherwise = b : deleteFirst a bc
No, it's not possible using a list comprehension. In a list comprehension you make a decision which element to keep based on that element only. In your example, you want to treat the first 3 you encounter differently than other 3s (because you only want to remove the first one), so the decision does not depend on the element alone. So a list comprehension won't work.
Your attempt using a recursive function is already pretty close, except that, as you said, it removes all instances. Why does it remove all instances? Because after you removed the first one, you call deleteFirst again on the rest of the list, which will remove the next instance and so on. To fix this, just do not call deleteFirst again after removing the first instance. So just use bc instead of deleteFirst a bc in that case.
as other already mentioned list comprehension is not an appropriate solution to this task (difficult to terminate the execution at one step).
You've almost written the correct solution, just in the case of equality with the matched value you had to terminate the computation by returning the rest of list without the matched element:
deleteFirst _ [] = []
deleteFirst a (b:bc) | a == b = bc
| otherwise = b : deleteFirst a bc
> print $ deleteFirst 3 (3:3:2:1:9:7:3:[])
> [3,2,1,9,7,3]
I don’t believe it is possible to do this with list comprehension (at least not in in any idiomatic way).
Your deleteFirst works almost. All you need to change to fix is is to stop deleting after the first match, i.e. replace deleteFirst a bc in the first clause by bc.
sepp2k's remarks about list comprehensions are an important thing to understand; list operations like map, filter, foldr and so on treat all list items uniformly, and the important thing to understand about them is what information is available at each step, and how each step's result is combined with those of other steps.
But the aspect I want to stress is that I think you should really be trying to solve these problems in terms of library functions. Adapting the solution from this older answer of mine to your problem:
deleteFirst x xs = beforeX ++ afterX
-- Split the list into two pieces:
-- * prefix = all items before first x
-- * suffix = all items after first x
where (beforeX, xAndLater) = break (/=x) xs
afterX = case xAndLater of
[] -> []
(_:xs) -> xs
The trick is that break already has the "up to first hit" behavior built in it. As a further exercise, you can try writing your own version of break; it's always instructive to learn how to write these small, generic and reusable functions.

Extract a from [a]

how can I easily take the following
[4]
and return the following:
4
I know that [4]!!0 works but doesn't seem to be a good strategy...
Just pattern match it:
getSingleton [a] = a
head is the normal answer, which you see three of (one with a custom name) - this is functionally the same as what you already know (x !! 0 ~ head x). I strongly suggest against partial functions unless you can prove (with local knowledge) that you'll never pass an empty list and result in a run-time exception.
If your function doesn't guarantee a non-empty list then use listToMaybe :: [a] -> Maybe a:
> listToMaybe [4]
Just 4
> listToMaybe [5,39,-2,6,1]
Just 5
> listToMaybe []
Nothing -- A 'Nothing' constructor instead of an exception
Once you have the Maybe a you can pattern match on that, keep it as Maybe and use fmap or a Maybe monad, or some other method to perform further operations.
Alternatively to gatoatigrado's solution you can also use the head function, which extracts the first element of a list, but will also work on lists with more than one element and additionally is a standard function in the Prelude. You just have to be careful not to apply it to empty lists or you will get a runtime exception.
Prelude> head [4]
4
Prelude> head []
*** Exception: Prelude.head: empty list
If you want this first item in a list you can just do
head [4]
[] is a monad. So you use the monad "extract" operation, <-
double x = 2*x
doubleAll xs = do x <- xs
return (double x)
Of course, the result of the monadic computation is returned in the monad. ;)