Haskell: A function that takes a list xs and an integer n and returns all list of length n with elements from xs - list

I have tried to solve this problem before, and I've searched for a solution and could never find one.
I need a function that takes a list xs and an integer n and returns all list of length n with elements from xs. For example:
function [0,1] 3 = [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
I have tried this:
list _ 0 = []
list xs n = do
y <- xs
ps <- list xs (n-1)
return y : ps
and this:
list _ 0 = []
list xs n = do
y <- xs
y : list xs (n-1)
None work as intended. I want to know two things:
Why doesn't these work?
How should I modify them so that they work?

You're very close! Your problem is your base case, list _ 0 = [].
What you're saying there is that there are no lists of length 0 with elements from xs, when in fact there is one, the empty list.
Try
list _ 0 = [[]]
list xs n = do
y <- xs
ps <- list xs (n-1)
return $ y : ps

Related

Count non-empty lists in a lists of lists

I am trying to count the number of non-empty lists in a list of lists with recursive code.
My goal is to write something simple like:
prod :: Num a => [a] -> a
prod [] = 1
prod (x:xs) = x * prod xs
I already have the deifniton and an idea for the edge condition:
nonEmptyCount :: [[a]] -> Int
nonEmptyCount [[]] = 0
I have no idea how to continue, any tips?
I think your base case, can be simplified. As a base-case, we can take the empty list [], not a singleton list with an empty list. For the recursive case, we can consider (x:xs). Here we will need to make a distinction between x being an empty list, and x being a non-empty list. We can do that with pattern matching, or with guards:
nonEmptyCount :: [[a]] -> Int
nonEmptyCount [] = 0
nonEmptyCount (x:xs) = -- …
That being said, you do not need recursion at all. You can first filter your list, to omit empty lists, and then call length on that list:
nonEmptyCount :: [[a]] -> Int
nonEmptyCount = length . filter (…)
here you still need to fill in ….
Old fashion pattern matching should be:
import Data.List
nonEmptyCount :: [[a]] -> Int
nonEmptyCount [] = 0
nonEmptyCount (x:xs) = if null x then 1 + (nonEmptyCount xs) else nonEmptyCount xs
The following was posted in a comment, now deleted:
countNE = sum<$>(1<$)<<<(>>=(1`take`))
This most certainly will look intimidating to the non-initiated, but actually, it is equivalent to
= sum <$> (1 <$) <<< (>>= (1 `take`))
= sum <$> (1 <$) . (take 1 =<<)
= sum . fmap (const 1) . concatMap (take 1)
= sum . map (const 1) . concat . map (take 1)
which is further equivalent to
countNE xs = sum . map (const 1) . concat $ map (take 1) xs
= sum . map (const 1) $ concat [take 1 x | x <- xs]
= sum . map (const 1) $ [ r | x <- xs, r <- take 1 x]
= sum $ [const 1 r | (y:t) <- xs, r <- take 1 (y:t)] -- sneakiness!
= sum [const 1 r | (y:_) <- xs, r <- [y]]
= sum [const 1 y | (y:_) <- xs]
= sum [ 1 | (_:_) <- xs] -- replace each
-- non-empty list
-- in
-- xs
-- with 1, and
-- sum all the 1s up!
= (length . (take 1 =<<)) xs
= (length . filter (not . null)) xs
which should be much clearer, even if in a bit sneaky way. It isn't recursive in itself, yes, but both sum and the list-comprehension would be implemented recursively by a given Haskell implementation.
This reimplements length as sum . (1 <$), and filter p xs as [x | x <- xs, p x], and uses the equivalence not (null xs) === (length xs) >= 1.
See? Haskell is fun. Even if it doesn't yet feel like it, but it will be. :)

Counting even number haskell with list comprehension?

I implemented a function that can count a list of numbers and produces how many even numbers in the list, I implemented using recursion, but I need this time with list comprehension.
I did try using list comprehension, but once I executed the function its just hang and it gives me nothing. Here is my code:
countEven :: (Integral t, Num a) => [t] -> a
countEven [] = 0
countEven (x:xs)
| ev == True = 1 + (countEven xs )
| otherwise = countEven xs
where ev = even x
This is my attempt using list comprehension :
evenList :: (Integral t, Num a) => [t] -> a
evenList xs = countEven [x | x <- [1..]]
List comprehensions can be used to produce other lists, but not counts. Thus, you need to combine a list comprehension with something else, e.g.
countEvens :: [Int] -> Int
countEvens l = length [ x | x <- l, even x ]
Here, the list comprehension just produces a sublist with all the even numbers, and length finishes the job.

Haskell count occurrences in two dimensional lists

I have to count the occurrences in a two dimensional (2D) list [[Int]], but I get errors.
What I tried so for is counting 1D. It works fine like this:
instances::Int->[Int]->Int
instances x [] = 0
instances x (y:ys)
| x==y = 1+(instances x ys)
| otherwise = instances x ys
Could you please help me to modify this function in order to count a 2D list:
instances::Int->[Int]->Int
Thanks in advance
Greetings
instances2D x = length . filter (==x) . concat
or
instances2D y xss = sum [1 | xs <- xss, x <- xs, y == x]
With your explicit recursion (v. a library function that hides the recursion), all you need is a function that can step through the elements of your 2D list. If you can write a function that steps through each element of your 2D list and gets each sub-list into a variable, then you can call your 1D function on that variable. And stepping through the elements of any list is easy with pattern matching:
matchesIn2DList:: Int -> [[Int]] -> Int
matchesIn2DList _ [] = 0 --> [] is an empty 2D list
matchesIn2DList x (l:ls) =
(matchesIn1DList x l) + (matchesIn2DList x ls)
Note that in the your base case:
instances x [] = 0
the value being searched for is immaterial: the count for the matches in an empty list will always be 0 no matter what value you are searching for, so you can use _ instead of a variable name.

Haskell Creating list of numbers

Hi
Im new to Haskell and wish to write a simple code.
I want to write a function which creates a list of numbers.
Where it starts of with 1 and increase with 2n+1 and 3n+1
so for example output should be like
take 6 myList = [1,3,4,7,9,10]
I think i need to use recursion but not sure how to do
it in list format.
Any help will be appreciated. Thanks
Actually, I am not sure if I get your idea.
But Is this what you want?
generator list = list ++ generator next
where
next = (map (\n -> 2 * n + 1) list) ++ (map (\n -> 3 * n + 1) list)
Oh, you can use generator [1] to fire up. like this:
take 100 $ generator [1]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) | x == y = x : merge xs ys
| x < y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
print $ take 10 $ merge [1,3..] [1,4..]
--[1,3,4,5,7,9,10,11,13,15]
As luqui said, we could use info such as do duplicates matter and does order matter. If the answers are no and no then a simple concatMap works fine:
myList = 1 : concatMap (\n -> 2*n+1 : 3*n+1 : []) myList
Results in:
> take 20 myList
[1,3,4,7,10,9,13,15,22,21,31,19,28,27,40,31,46,45,67,43]
If the answers are yes and yes then I imagine it could be cleaner, but this is sufficient:
myList = abs
where
abs = merge as bs
as = 1 : map (\n -> 2*n+1) abs
bs = 1 : map (\n -> 3*n+1) abs
merge (x:xs) (y:ys)
| x == y = x : merge xs ys
| x < y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
Results in:
> take 20 myList
[1,3,4,7,9,10,13,15,19,21,22,27,28,31,39,40,43,45,46,55]

Checking the contents of a char list list in sml

My question is like the one here.
I'm working on a char list list and I need to check that 1-9 are used once in every list, but also once in every position in the list.
My code looks like this:
infix member
fun x member [] = false
| x member (y::ys) = x = y orelse x member ys;
fun rscheck xs =
let
val ys = [#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9"]
in
ys member xs
end;
but this only checks if 1-9 are members of the lists, not if they're on the same position in different lists.
I had the idea to use this function:
fun poslist xs n = map (fn x => List.nth (x , n)) xs;
(the function poslist is supposed to return whatever is in position n of the list xs, so I can isolate the individual lists in the char list list), but since poslist returns a char list rscheck can't work with it as it needs a char list list.
1) Can I improve poslist?
2) How do I fix rscheck?
Edit
infix member
fun x member [] = false
| x member (y::ys) = x = y orelse x member ys;
fun samelist (x::xs) ys = x member ys andalso samelist xs ys
| samelist [] _ = true;
fun takelist xs n = map (fn x => List.nth (x , n)) xs;
fun reverse xs = List.tabulate (9 , fn x => takelist xs x);
fun rscheck xs =
let
val s = [#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9"]
in
List.all (fn x => samelist s x) xs
end andalso rscheck (reverse xs);
Your rscheck method just checks whether one of the rows is equal to [#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9"]. What it should do is check that all the rows contain the numbers in any order. Once you fix that you can solve the rest of the problem as follows:
The easiest way to check whether a matrix is a valid sudoku solution is to use your rscheck function on it, then transpose it (i.e. switch its rows and columns) and then use your rscheck on the transposed matrix. If it returns true both times, it's a valid sudoku solution.
To transpose the matrix you can either translate this OCaml code to SML, or simply use your poslist function for all indices from 0 to 8.