Getting `head: empty list` error while trying to transpose a matrix - haskell

I wrote this program which is supposed to return the transposition of a matrix of integers.
trans:: [[Int]]-> [[Int]]
trans [[]]=[[]]
trans xss=[(transHead xss)] ++ trans(transTail xss)
transHead:: [[Int]]->[Int]
transHead []=[]
transHead [[a],[b]]=[a] ++ [b]
transHead xss= [head(head xss)] ++ transHead (tail xss)
transTail:: [[Int]]-> [[Int]]
transTail []=[]
transTail xss= [tail(head xss)] ++ transTail(tail xss)
The program compiles but it errors with "Main: Prelude.head: empty list"
Can you please help me to find a solution.

It is usually not a good idea to work with head and tail: it is better to work with pattern matching here. Then the compiler can also show what patterns are not covered.
trans:: [[Int]] -> [[Int]]
trans [[]] = [[]]
trans xss = [transHead xss] ++ trans (transTail xss)
transHead:: [[Int]] -> [Int]
transHead [] = []
transHead [[a], [b]] = [a] ++ [b]
transHead ((x : _) : xss) = [x] ++ transHead xss
transTail:: [[Int]] -> [[Int]]
transTail [] = []
transTail ((_:xs):xss) = [xs] ++ transTail xss
If we compile this, we get the following compiler warnings:
<interactive>:7:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘transHead’: Patterns not matched: ([]:_)
<interactive>:12:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘transTail’: Patterns not matched: ([]:_)
Your transHead and transTail thus do not cover the case where the first item of the list of lists of items is empty.

Related

program which calculate the multiplication of two matrixes in haskell

I wrote this program which has to multiply two matrixes but it says (empty list in tail), I guess my recurrence conditions are wrong but as a begginner, I don't realy see the problem, can you help me ? I think someone with enaugh experience will see the problem in 2 secondes.
multVecttt :: [Int]-> [Int] -> Int -- multiply a vector with a vector
multVecttt [][]=0
multVecttt [] _=0
multVecttt [a] [b]=a*b
multVecttt xs ys= (head xs) * (head ys) + multVecttt (tail xs) (tail ys)
multVectMat :: [Int]-> [[Int]] -> [Int]-- multiply a vector with a matrix using hadamard multiplication of matrixes
multVectMat [] [[a]]=[a]
multVectMat [][]=[]
multVectMat [] _=[]
multVectMat _ []=[]
multVectMat xs (ys: [[]]) = [multVecttt xs ys]
multVectMat xs yss= [multVecttt xs (head yss)] ++ multVectMat xs (tail yss)
multMatrix :: [[Int]] -> [[Int]] -> [[Int]]-- multiply two matrixes
multMatrix [][]=[]
multMatrix [][[a]]=[[a]]
multMatrix [[a]] [[b]]= [[a*b]]
multMatrix (xs: [[]]) yss = [multVectMat xs yss]
multMatrix xss yss = [multVectMat (head xss) (trans yss)] ++ multMatrix (tail xss) yss
trans:: [[Int]]-> [[Int]]-- return the transpose of a matrix
trans [[]]=[[]]
trans [[a],[b]]=[[a] ++ [b]]
trans xss=[(transHead xss)] ++ trans(transTail xss)
transHead:: [[Int]]->[Int]
transHead []=[]
transHead [[a],[b]]=[a] ++ [b]
transHead xss= [head(head xss)] ++ transHead (tail xss)
transTail:: [[Int]]-> [[Int]]
transTail []=[]
transTail xss= [tail(head xss)] ++ transTail(tail xss)
I wrote comments to make sure tou understand what are the functions doing
it compiles, but I have an execution error which is : Prelude.tail: empty list
My recommendation is to eliminate all calls to tail with pattern matching. Then you can ask GHC to tell you where you went wrong. For example:
multMatrix xss yss = [multVectMat (head xss) (trans yss)] ++ multMatrix (tail xss) yss
can become:
multMatrix (xs:xss) yss = [multVectMat xs (trans yss)] ++ multMatrix xss yss
Do similarly for the other calls to tail and you can lean on automated tooling to help you find your mistake. Nice!

Why is my implementation of inits failing?

Here's how I've implemented it:
inits' :: [a] -> [[a]]
inits' [] = [[]]
inits' xs = inits'(init xs) : xs
I get this error:
• Couldn't match type ‘a’ with ‘[[a]]’
‘a’ is a rigid type variable bound by
the type signature for:
inits' :: forall a. [a] -> [[a]]
Expected type: [[[a]]]
Actual type: [a]
• In the second argument of ‘(:)’, namely ‘xs’
In the expression: inits' (init xs) : xs
In an equation for ‘inits'’: inits' xs = inits' (init xs) : xs
seems that to produce inits I'd have to call init on every sublist. What am I doing wrong?
It seems like you've designed this as a mirrored version of
tails' :: [a] -> [[a]]
tails' [] = [[]]
tails' xs = xs : tails' (tail xs)
The reason that works is that the : operator prepends a single element xs to a list. This could also be written
tails' xs = [xs] ++ tails' (tail xs)
But in inits'(init xs) : xs, this doesn't apply: the single element would be inits'(init xs), but that's in fact already a nested list. The ++ version would however work:
inits' xs = inits'(init xs) ++ [xs]
Mind, this is pretty inefficient, because ++ always needs to traverse the entire LHS list, and this happens over and over in the recursion.

List of prefixes in haskell

I am to write a function which returns a list of all prefixes of a given string.
This is where I'm at so far.
prefixess [x] [] = [x]
prefixess [] s = prefixess [s] s
prefixess [x] s = prefixess [x, (init s)] (init s)
prefixes s = prefixess [] s
It compiles, but when I try running it on a string I get this:
Couldn't match type ‘Char’ with ‘[t]’
Expected type: [[t]]
Actual type: [Char]
Relevant bindings include
it :: [t] -> [[t]] (bound at <interactive>:18:1)
In the first argument of ‘prefixess’, namely ‘"abcde"’
In the expression: prefixess "abcde"
In an equation for ‘it’: it = prefixess "abcde"
I am out of ideas. Any hints?
I don't think this code does what you think it does. You try to pattern match the list x with the pattern [x], which captures the element of a singleton list. If i fix your code like this, it works:
prefixess x [] = x
prefixess [] s = prefixess [s] s
prefixess x s = prefixess ((init s):x) (init s)
prefixes s = prefixess [] s
This gives the following result:
Main> prefixes "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]
But you don't really need an accumulator for a function which calculates prefixes, I would write it like this:
prefixes' (x:xs) = [] : (map (x:) (prefixes' xs))
prefixes' [] = [[]]
This function is also available under the name "inits" in Data.List
Main> import Data.List
Main Data.List> inits "stackoverflow"
["","s","st","sta","stac","stack","stacko","stackov","stackove","stackover","stackoverf","stackoverfl","stackoverflo","stackoverflow"]
Point-free style solution for genereting list of all prefixes:
prefixes = foldr (\el acc -> [] : map (el:) acc) [[]]

interleaving two strings, preserving order: functional style

In this question, the author brings up an interesting programming question: given two string, find possible 'interleaved' permutations of those that preserves order of original strings.
I generalized the problem to n strings instead of 2 in OP's case, and came up with:
-- charCandidate is a function that finds possible character from given strings.
-- input : list of strings
-- output : a list of tuple, whose first value holds a character
-- and second value holds the rest of strings with that character removed
-- i.e ["ab", "cd"] -> [('a', ["b", "cd"])] ..
charCandidate xs = charCandidate' xs []
charCandidate' :: [String] -> [String] -> [(Char, [String])]
charCandidate' [] _ = []
charCandidate' ([]:xs) prev =
charCandidate' xs prev
charCandidate' (x#(c:rest):xs) prev =
(c, prev ++ [rest] ++ xs) : charCandidate' xs (x:prev)
interleavings :: [String] -> [String]
interleavings xs = interleavings' xs []
-- interleavings is a function that repeatedly applies 'charCandidate' function, to consume
-- the tuple and build permutations.
-- stops looping if there is no more tuple from charCandidate.
interleavings' :: [String] -> String -> [String]
interleavings' xs prev =
let candidates = charCandidate xs
in case candidates of
[] -> [prev]
_ -> concat . map (\(char, ys) -> interleavings' ys (prev ++ [char])) $ candidates
-- test case
input :: [String]
input = ["ab", "cd"]
-- interleavings input == ["abcd","acbd","acdb","cabd","cadb","cdab"]
it works, however I'm quite concerned with the code:
it is ugly. no point-free!
explicit recursion and additional function argument prev to preserve states
using tuples as intermediate form
How can I rewrite the above program to be more "haskellic", concise, readable and more conforming to "functional programming"?
I think I would write it this way. The main idea is to treat creating an interleaving as a nondeterministic process which chooses one of the input strings to start the interleaving and recurses.
Before we start, it will help to have a utility function that I have used countless times. It gives a convenient way to choose an element from a list and know which element it was. This is a bit like your charCandidate', except that it operates on a single list at a time (and is consequently more widely applicable).
zippers :: [a] -> [([a], a, [a])]
zippers = go [] where
go xs [] = []
go xs (y:ys) = (xs, y, ys) : go (y:xs) ys
With that in hand, it is easy to make some non-deterministic choices using the list monad. Notionally, our interleavings function should probably have a type like [NonEmpty a] -> [[a]] which promises that each incoming string has at least one character in it, but the syntactic overhead of NonEmpty is too annoying for a simple exercise like this, so we'll just give wrong answers when this precondition is violated. You could also consider making this a helper function and filtering out empty lists from your top-level function before running this.
interleavings :: [[a]] -> [[a]]
interleavings [] = [[]]
interleavings xss = do
(xssL, h:xs, xssR) <- zippers xss
t <- interleavings ([xs | not (null xs)] ++ xssL ++ xssR)
return (h:t)
You can see it go in ghci:
> interleavings ["abc", "123"]
["abc123","ab123c","ab12c3","ab1c23","a123bc","a12bc3","a12b3c","a1bc23","a1b23c","a1b2c3","123abc","12abc3","12ab3c","12a3bc","1abc23","1ab23c","1ab2c3","1a23bc","1a2bc3","1a2b3c"]
> interleavings ["a", "b", "c"]
["abc","acb","bac","bca","cba","cab"]
> permutations "abc" -- just for fun, to compare
["abc","bac","cba","bca","cab","acb"]
This is fastest implementation I've come up with so far. It interleaves a list of lists pairwise.
interleavings :: [[a]] -> [[a]]
interleavings = foldr (concatMap . interleave2) [[]]
This horribly ugly mess is the best way I could find to interleave two lists. It's intended to be asymptotically optimal (which I believe it is); it's not very pretty. The constant factors could be improved by using a special-purpose queue (such as the one used in Data.List to implement inits) rather than sequences, but I don't feel like including that much boilerplate.
{-# LANGUAGE BangPatterns #-}
import Data.Monoid
import Data.Foldable (toList)
import Data.Sequence (Seq, (|>))
interleave2 :: [a] -> [a] -> [[a]]
interleave2 xs ys = interleave2' mempty xs ys []
interleave2' :: Seq a -> [a] -> [a] -> [[a]] -> [[a]]
interleave2' !prefix xs ys rest =
(toList prefix ++ xs ++ ys)
: interleave2'' prefix xs ys rest
interleave2'' :: Seq a -> [a] -> [a] -> [[a]] -> [[a]]
interleave2'' !prefix [] _ = id
interleave2'' !prefix _ [] = id
interleave2'' !prefix xs#(x : xs') ys#(y : ys') =
interleave2' (prefix |> y) xs ys' .
interleave2'' (prefix |> x) xs' ys
Using foldr over interleave2
interleave :: [[a]] -> [[a]]
interleave = foldr ((concat .) . map . iL2) [[]] where
iL2 [] ys = [ys]
iL2 xs [] = [xs]
iL2 (x:xs) (y:ys) = map (x:) (iL2 xs (y:ys)) ++ map (y:) (iL2 (x:xs) ys)
Another approach would be to use the list monad:
interleavings xs ys = interl xs ys ++ interl ys xs where
interl [] ys = [ys]
interl xs [] = [xs]
interl xs ys = do
i <- [1..(length xs)]
let (h, t) = splitAt i xs
map (h ++) (interl ys t)
So the recursive part will alternate between the two lists, taking all from 1 to N elements from each list in turns and then produce all possible combinations of that. Fun use of the list monad.
Edit: Fixed bug causing duplicates
Edit: Answer to dfeuer. It turned out tricky to do code in the comment field. An example of solutions that do not use length could look something like:
interleavings xs ys = interl xs ys ++ interl ys xs where
interl [] ys = [ys]
interl xs [] = [xs]
interl xs ys = splits xs >>= \(h, t) -> map (h ++) (interl ys t)
splits [] = []
splits (x:xs) = ([x], xs) : map ((h, t) -> (x:h, t)) (splits xs)
The splits function feels a bit awkward. It could be replaced by use of takeWhile or break in combination with splitAt, but that solution ended up a bit awkward as well. Do you have any suggestions?
(I got rid of the do notation just to make it slightly shorter)
Combining the best ideas from the existing answers and adding some of my own:
import Control.Monad
interleave [] ys = return ys
interleave xs [] = return xs
interleave (x : xs) (y : ys) =
fmap (x :) (interleave xs (y : ys)) `mplus` fmap (y :) (interleave (x : xs) ys)
interleavings :: MonadPlus m => [[a]] -> m [a]
interleavings = foldM interleave []
This is not the fastest possible you can get, but it should be good in terms of general and simple.

"non-Exhaustive patterns in function listelem" haskell

Hi i'm very new to haskell. I'm trying to write a code that will allow me to enter a list of coordinate systems (CS1) (i.e a list of list of coordinates) and a list of all coordinates (CL) that are not allowed. The aim of the function is to discard all coordinate systems in CS1 that contain atleast 1 of these coordinates in CL, ending up with a smaller subset of coordinate systems(CS2) from CS1. (confusing? i'm sorry)
I think i'm quite close to crack the nut (although i really don't know as i'm in the trail error stage), but i'm having a non-Exhaustive problem when i run listelem2 it complains on listelem. Can anyone see what i'm missing? Thanks for any help you can give! :D
listelem0 :: (Eq a) => [a] -> a -> [a]
listelem0 [] y = []
listelem0 (x:xs) y
| x == y = []
| x /= y = [x] ++ listelem0 xs y
listelem :: (Eq a) => [a] -> a -> [a]
listelem (x:xs) y
| length (listelem0 (x:xs) y) < length (x:xs) = []
| otherwise = listelem0 (x:xs) y
listelem1 :: (Eq a) => [[a]] -> a -> [[a]]
listelem1 [] y = []
listelem1 (x:xs) y = [listelem x y] ++ listelem1 xs y
listelem2 :: (Eq a) => [[a]] -> [a] -> [[a]]
listelem2 [] [] = [[]]
listelem2 (x:xs) [] = (x:xs)
listelem2 (x:xs) (y:ys) = listelem2 (listelem1 (x:xs) y) ys
Emil is right, that you're missing those 2 patterns, but here's how you can find those missing patterns yourself:
If you run ghci -Wall yourFile.hs (or ghci -fwarn-incomplete-patterns yourFile.hs), you'll see all the incomplete patterns:
[1 of 1] Compiling Main ( /tmp/ls.hs, interpreted )
/tmp/ls.hs:2:1:
Warning: Pattern match(es) are non-exhaustive
In an equation for `listelem0': Patterns not matched: (_ : _) _
/tmp/ls.hs:8:1:
Warning: Pattern match(es) are non-exhaustive
In an equation for `listelem': Patterns not matched: [] _
/tmp/ls.hs:17:1:
Warning: Pattern match(es) are non-exhaustive
In an equation for `listelem2': Patterns not matched: [] (_ : _)
Ok, modules loaded: Main.
Let's take the last one for example: In an equation for listelem2': Patterns not matched: [] (_ : _) -- this means just what it sounds like: that the pattern listelem2 [] (something:somethingElse) is never matched.
You have no patterns for these calls:
listelem [] y
listelem2 [] (y:ys)

Resources