Related
Trying to return a list with the last element removed. Why am I getting this error?
ERROR file:.\ShrinkByOne.hs:5 - Type error in application
*** Expression : (lis !! n : result) lis n
*** Term : (:)
*** Type : f -> [f] -> [f]
*** Does not match : a -> b -> c -> d -> e
shrinkByOne :: [Int] -> [Int] -> Int -> [Int]
shrinkByOne result lis n
| n <= ((length lis) - 2) = shrinkByOne ( ((lis !! n):result) lis n+1) -- this condition prevents the last element from being returned
| otherwise = result
Why the error?
In your original code, you had something like that:
shrinkByOne (... something ...)
which meant that you applied only one argument to shrinkByOne. You need this instead:
shrinkByOne (... something ...) (... something ...) (... something ...)
Therefore, put parentheses this way:
shrinkByOne :: [Int] -> [Int] -> Int -> [Int]
shrinkByOne result lis n
| n <= ((length lis) - 2) = shrinkByOne ((lis !! n):result) lis (n+1) -- this condition prevents the last element from being returned
| otherwise = result
Other remarks
However, you will still not get the desired result, as the result will be reversed and the !! is expensive, and your function will be of Θ(n²) complexity.
Try a much simpler, linear approach:
shrinkByOne' :: [Int] -> [Int]
shrinkByOne' [x] = []
shrinkByOne' (x : xs) = x : shrinkByOne' xs
Finally, I understand that this is an exercise to learn Haskell. If it's not, simply use the init function from the Prelude.
First, you want to leave out unneeded parens around function arguments. f(x) is written f x in Haskell (that one's just optional), and in particular you can't write g (x y) if g :: A -> B -> C, it needs to be g x y (or possibly g (x) (y). But g (x y) would mean, you apply the function x to the argument y, and use the result as argument for g. (If you actually want that, write g $ x y, or g . x $ y.)
So that would mean shrinkByOne ((lis !! n):result) lis n+1. Which would, however, be parsed as (shrinkByOne ((lis !! n):result) lis n) + 1: infix operators like + always have lower precedence than function application, so indeed around n+1 you do need parens.
I'm writing a program in Haskell that generates random triads of ints in order to play them as chords using Euterpea. Here's what my list of lists looks like (obviously, it's infinite, but I'll take 10 $ chop 3 $ randInts, where chop is just a function that splits a list up into (ordered) groupings of three and randPitch simply generates ints over the interval 24 - 84):
[[27,33,48],[53,59,82],[31,49,62],[50,60,63],[51,56,79],[57,59,60],[52,63,69],[52,77,79],[32,32,37],[39,77,84]]
To learn a bit about music theory, I'm applying various filters to these triads. The one that's giving me trouble (at least to implement in Haskell, which is a new language for me) is what Dmitri Tymoczko would call "conjunct melodic notation"--i.e., melodies (in this case the top 'note' or pitch of the 3-tuple) should only move short distances.
What I want to do is write a function that recursively filters the endless list of triads such that what results is a list of triads whose top note only moves by <= n between each chord: essentially, a kind of random walk where you are only allowed to move n semitones for any one step. Here are the functions I have so far:
jumpSize :: (Num a, Ord a) => [[a]] -> [[a]]
jumpSize (_:[]) = []
jumpSize (x:y:[]) = (abs (maximum x - maximum y) : x) : []
jumpSize (x:y:zs) = (abs (maximum x - maximum y) : x) : jumpSize (y:zs)
This will prepend the distance from triad x to y at the beginning of list x. So take 5 $ jumpSize $ chop 3 $ randPitch gives me:
[[34,27,33,48],[20,53,59,82],[1,31,49,62],[16,50,60,63],[19,51,56,79]]
I tried to write a recursive function that filters out all the chords with jumps of great than n, recalculates the new jumpSizes and then applies itself again. However, I'm having trouble because this function is either crashing GHCi or giving me all sorts of problems. Structurally, I would like to still produce the chords by filtering over the random array, but I think I'm missing something about how to best do this in a functional language. Maybe I need to supply an initial generator chord? Thanks!
jumpRecur :: (Num a, Ord a) => a -> [[a]] -> [[a]]
jumpRecur n (xs)
| [x | x <- xs, head x > n] == [] = xs
| otherwise = jumpRecur n $ jumpSize $ filter (\x -> head x <= n) xs
Here's a sample output:
*Main> jumpRecur 5 $ jumpSize $ chop 3 $ take 1000 $ randPitch
[[2,2,2,2,2,2,2,2,70,70,76],[1,1,1,1,1,1,1,1,55,74,74],[1,1,1,1,1,1,1,5,26,28,73], [3,3,3,3,3,3,0,1,26,69,74],[5,5,5,5,5,5,5,5,33,43,77],[0,0,0,0,0,0,0,0,47,67,82],[2,2,2,2,2,2,4,4,37,66,82],[3,3,3,3,3,3,3,3,59,69,84],[4,4,4,4,4,4,4,4,59,79,81],[4,4,5,5,5,5,5,5,28,69,77],[5,5,5,5,5,5,5,5,54,68,73],[0,0,0,0,0,0,0,0,32,73,78],[5,5,5,5,5,5,1,4,52,62,78],[0,0,0,0,0,0,0,0,58,71,73],[3,3,3,3,3,3,4,4,25,64,73],[1,1,1,1,1,3,3,3,35,42,76],[4,4,4,4,4,4,4,4,35,39,77]]
It's probably good Haskell idiom to generalize the filter, as follows:
jumpBy :: (a -> a -> Bool) -> [a] -> [a]
jumpBy ok (x:y:zs) | ok x y = x:jumpBy ok (y:zs) -- accept y & step
| otherwise = jumpBy ok (x:zs) -- reject y & retry
jumpBy _ xs = xs
If you are sure all input will be infinite lists, you don't really need that last line which handles the ends of finite lists, but it's good practice to handle all cases.
Then, use your general filter with your specific test:
jumpSize = jumpBy (\x y -> abs(maximum x - maximum y) < n)
I want to define a simple function in Haskell:
nzp :: [Int] -> (Int,Int,Int)
that accepts a list of integers as input and returns a triple (a,b,c) where a is the amount of numbers in the list less than 0, b is the amount equal to 0 and c is the amount higher than zero. For example,
nzp [3,0,-2,0,4,5] = (1,2,3)
I have to define this function recursively and I can only traverse the list once. How can I do this? I can't seem to grasp the concept of recursively creating a tuple.
Most Regards
Here are some pointers:
To use recursion to build up a value, you need to pass the previous version of the value as an argument, so write
nzp_helper :: [Int] -> (Int,Int,Int) -> (Int, Int, Int)
Decide what the answer is when the list is empty
nzp_helper [] runningTotals = -- what's the answer if the list is empty?
Decide what the answer is when there's something in the list
nzp_helper (i:is) (negatives, positives, zeros) =
| i < 0 = -- write stuff here
| i == 0 = -- I hope you're getting the idea
Kick the whole thing off by defining nzp using nzp_helper.
nzp is = nzp_helper is -- one final argument - what?
Instead of thinking of trying to create a single tuple recursively, you should think about updating an existing tuple containing the counts based on given value. This function would look something like:
update :: (Int, Int, Int) -> Int -> (Int, Int, Int)
update (l,e,g) x | x < 0 = (l+1, e, g)
update (l,e,g) x | x == 0 = (l, e+1, g)
update (l,e,g) x | x > 0 = (l, e, g+1)
Then you can traverse the input list using foldl and accumulate the output tuple:
nzp :: [Int] -> (Int, Int, Int)
nzp = foldl update (0,0,0)
EDIT: As #leftroundabout points out in the comments, you should avoid using foldl since it can lead to space leaks - you can find an explanation in Real World Haskell. You can use the strict version of foldl, foldl' in Data.List
import Data.List
nzp = foldl' update (0,0,0)
I can't seem to grasp the concept of recursively creating a tuple.
I shouldn't think so – in fact, it's impossible! (At least not without GHC extension havoc.)
No, you need to create a tuple in one go. The important thing needed for your function: since you may only traverse the list once, you need to pull through the entire tuple at once as well. As this is apparently homework, I shall instead show how it works with a fold (that is in fact preferrable, but translates quite directly to recursion):
nzp = foldr switchIncr (0,0,0)
where switchIncr x (negatives, zeroes, positives)
| x<0 = (succ negatives, zeroes, positives)
| x==0 = (negatives, succ zeroes, positives)
| otherwise = (negatives, zeroes, succ positives)
New to Haskell too! Perhaps not proper but here is my solution which works.
Define an auxiliary function that accumulates the n,z, and p values
let f (x:xs, (n, z, p)) | x < 0 = f (xs, (n+1, z, p))
| x == 0 = f (xs, (n, z+1, p))
| otherwise = f (xs, (n, z, p+1))
f ([], (n, z, p)) = ([], (n, z, p))
and define nzp in terms of the auxiliary function
let nzp x = snd $ f (x,(0,0,0))
to verify
Prelude> nzp [-1,1,1,-1,0]
(2,1,2)
I am a little over a couple of months into Haskell. A helper/auxilliary function would make running this solution easier.
s3 [] (l,g,z) = (l,g,z)
s3 (x:xs) (l,g,z) = if x<0
then (s3 xs (l+1,g,z))
else if x>0
then (s3 xs (l,g+1,z))
else (s3 xs (l,g,z+1))
This is run with s3 [1,0,-2,3,4,-7,0,-8] (0,0,0) producing
(3,3,2).
Just about any primitive recursive function can be translated into a fold.
I want to iterate 2 (or 3) infinite lists and find the "smallest" pair that satisfies a condition, like so:
until pred [(a,b,c) | a<-as, b<-bs, c<-cs]
where pred (a,b,c) = a*a + b*b == c*c
as = [1..]
bs = [1..]
cs = [1..]
The above wouldn't get very far, as a == b == 1 throughout the run of the program.
Is there a nice way to dovetail the problem, e.g. build the infinite sequence [(1,1,1),(1,2,1),(2,1,1),(2,1,2),(2,2,1),(2,2,2),(2,2,3),(2,3,2),..] ?
Bonus: is it possible to generalize to n-tuples?
There's a monad for that, Omega.
Prelude> let as = each [1..]
Prelude> let x = liftA3 (,,) as as as
Prelude> let x' = mfilter (\(a,b,c) -> a*a + b*b == c*c) x
Prelude> take 10 $ runOmega x'
[(3,4,5),(4,3,5),(6,8,10),(8,6,10),(5,12,13),(12,5,13),(9,12,15),(12,9,15),(8,15,17),(15,8,17)]
Using it's applicative features, you can generalize to arbitrary tuples:
quadrupels = (,,,) <$> as <*> as <*> as <*> as -- or call it liftA4
But: this alone does not eliminate duplication, of course. It only gives you proper diagonalization. Maybe you could use monad comprehensions together with an approach like Thomas's, or just another mfilter pass (restricting to b /= c, in this case).
List comprehensions are great (and concise) ways to solve such problems. First, you know you want all combinations of (a,b,c) that might satisfy a^2 + b^2 = c^2 - a helpful observation is that (considering only positive numbers) it will always be the case that a <= c && b <= c.
To generate our list of candidates we can thus say c ranges from 1 to infinity while a and b range from one to c.
[(a,b,c) | c <- [1..], a <- [1..c], b <- [1..c]]
To get to the solution we just need to add your desired equation as a guard:
[(a,b,c) | c <- [1..], a <- [1..c], b <- [1..c], a*a+b*b == c*c]
This is inefficient, but the output is correct:
[(3,4,5),(4,3,5),(6,8,10),(8,6,10),(5,12,13),(12,5,13),(9,12,15)...
There are more principled methods than blind testing that can solve this problem.
{- It depends on what is "smallest". But here is a solution for a concept of "smallest" if tuples were compared first by their max. number and then by their total sum. (You can just copy and paste my whole answer into a file as I write the text in comments.)
We will need nub later. -}
import Data.List (nub)
{- Just for illustration: the easy case with 2-tuples. -}
-- all the two-tuples where 'snd' is 'n'
tuples n = [(i, n) | i <- [1..n]]
-- all the two-tuples where 'snd' is in '1..n'
tuplesUpTo n = concat [tuples i | i <- [1..n]]
{-
To get all results, you will need to insert the flip of each tuple into the stream. But let's do that later and generalize first.
Building tuples of arbitrary length is somewhat difficult, so we will work on lists. I call them 'kList's, if they have a length 'k'.
-}
-- just copied from the tuples case, only we need a base case for k=1 and
-- we can combine all results utilizing the list monad.
kLists 1 n = [[n]]
kLists k n = do
rest <- kLists (k-1) n
add <- [1..head rest]
return (add:rest)
-- same as above. all the klists with length k and max number of n
kListsUpTo k n = concat [kLists k i | i <- [1..n]]
-- we can do that unbounded as well, creating an infinite list.
kListsInf k = concat [kLists k i | i <- [1..]]
{-
The next step is rotating these lists around, because until now the largest number is always in the last place. So we just look at all rotations to get all the results. Using nub here is admittedly awkward, you can improve that. But without it, lists where all elements are the same are repeated k times.
-}
rotate n l = let (init, end) = splitAt n l
in end ++ init
rotations k l = nub [rotate i l | i <- [0..k-1]]
rotatedKListsInf k = concatMap (rotations k) $ kListsInf k
{- What remains is to convert these lists into tuples. This is a bit awkward, because every n-tuple is a separate type. But it's straightforward, of course. -}
kListToTuple2 [x,y] = (x,y)
kListToTuple3 [x,y,z] = (x,y,z)
kListToTuple4 [x,y,z,t] = (x,y,z,t)
kListToTuple5 [x,y,z,t,u] = (x,y,z,t,u)
kListToTuple6 [x,y,z,t,u,v] = (x,y,z,t,u,v)
{- Some tests:
*Main> take 30 . map kListToTuple2 $ rotatedKListsInf 2
[(1,1),(1,2),(2,1),(2,2),(1,3),(3,1),(2,3),(3,2),(3,3),(1,4),(4,1),(2,4),(4,2),(3,4),
(4,3),(4,4),(1,5),(5,1),(2,5),(5,2),(3,5),(5,3),(4,5),(5,4),(5,5),(1,6),(6,1),
(2,6), (6,2), (3,6)]
*Main> take 30 . map kListToTuple3 $ rotatedKListsInf 3
[(1,1,1),(1,1,2),(1,2,1),(2,1,1),(1,2,2),(2,2,1),(2,1,2),(2,2,2),(1,1,3),(1,3,1),
(3,1,1),(1,2,3),(2,3,1),(3,1,2),(2,2,3),(2,3,2),(3,2,2),(1,3,3),(3,3,1),(3,1,3),
(2,3,3),(3,3,2),(3,2,3),(3,3,3),(1,1,4),(1,4,1),(4,1,1),(1,2,4),(2,4,1),(4,1,2)]
Edit:
I realized there is a bug: Just rotating the ordered lists isn't enough of course. The solution must be somewhere along the lines of having
rest <- concat . map (rotations (k-1)) $ kLists (k-1) n
in kLists, but then some issues with repeated outputs arise. You can figure that out, I guess. ;-)
-}
It really depends on what you mean by "smallest", but I assume you want to find a tuple of numbers with respect to its maximal element - so (2,2) is less than (1,3) (while standard Haskell ordering is lexicographic).
There is package data-ordlist, which is aimed precisely at working with ordered lists. It's function mergeAll (and mergeAllBy) allows you to combine a 2-dimensional matrix ordered in each direction into an ordered list.
First let's create a desired comparing function on tuples:
import Data.List (find)
import Data.List.Ordered
compare2 :: (Ord a) => (a, a) -> (a, a) -> Ordering
compare2 x y = compare (max2 x, x) (max2 y, y)
where
max2 :: Ord a => (a, a) -> a
max2 (x, y) = max x y
Then using mergeAll we create a function that takes a comparator, a combining function (which must be monotonic in both arguments) and two sorted lists. It combines all possible elements from the two lists using the function and produces a result sorted list:
mergeWith :: (b -> b -> Ordering) -> (a -> a -> b) -> [a] -> [a] -> [b]
mergeWith cmp f xs ys = mergeAllBy cmp $ map (\x -> map (f x) xs) ys
With this function, it's very simple to produce tuples ordered according to their maximum:
incPairs :: [(Int,Int)]
incPairs = mergeWith compare2 (,) [1..] [1..]
Its first 10 elements are:
> take 10 incPairs
[(1,1),(1,2),(2,1),(2,2),(1,3),(2,3),(3,1),(3,2),(3,3),(1,4)]
and when we (for example) look for the first pair whose sum of squares is equal to 65:
find (\(x,y) -> x^2+y^2 == 65) incPairs
we get the correct result (4,7) (as opposed to (1,8) if lexicographic ordering were used).
This answer is for a more general problem for a unknown predicate. If the predicate is known, more efficient solutions are possible, like others have listed solutions based on knowledge that you don't need to iterate for all Ints for a given c.
When dealing with infinite lists, you need to perform breadth-first search for solution. The list comprehension only affords depth-first search, that is why you never arrive at a solution in your original code.
counters 0 xs = [[]]
counters n xs = concat $ foldr f [] gens where
gens = [[x:t | t <- counters (n-1) xs] | x <- xs]
f ys n = cat ys ([]:n)
cat (y:ys) (x:xs) = (y:x): cat ys xs
cat [] xs = xs
cat xs [] = [xs]
main = print $ take 10 $ filter p $ counters 3 [1..] where
p [a,b,c] = a*a + b*b == c*c
counters generates all possible counters for values from the specified range of digits, including a infinite range.
First, we obtain a list of generators of valid combinations of counters - for each permitted digit, combine it with all permitted combinations for counters of smaller size. This may result in a generator that produces a infinite number of combinations. So, we need to borrow from each generator evenly.
So gens is a list of generators. Think of this as a list of all counters starting with one digit: gens !! 0 is a list of all counters starting with 1, gens !! 1 is a list of all counters starting with 2, etc.
In order to borrow from each generator evenly, we could transpose the list of generators - that way we would get a list of first elements of the generators, followed by a list of second elements of the generators, etc.
Since the list of generators may be infinite, we cannot afford to transpose the list of generators, because we may never get to look at the second element of any generator (for a infinite number of digits we'd have a infinite number of generators). So, we enumerate the elements from the generators "diagonally" - take first element from the first generator; then take the second element from the first generator and the first from the second generator; then take the third element from the first generator, the second from the second, and the first element from the third generator, etc. This can be done by folding the list of generators with a function f, which zips together two lists - one list is the generator, the other is the already-zipped generators -, the beginning of one of them being offset by one step by adding []: to the head. This is almost zipWith (:) ys ([]:n) - the difference is that if n or ys is shorter than the other one, we don't drop the remainder of the other list. Note that folding with zipWith (:) ys n would be a transpose.
For this answer I will take "smallest" to refer to the sum of the numbers in the tuple.
To list all possible pairs in order, you can first list all of the pairs with a sum of 2, then all pairs with a sum of 3 and so on. In code
pairsWithSum n = [(i, n-i) | i <- [1..n-1]]
xs = concatMap pairsWithSum [2..]
Haskell doesn't have facilities for dealing with n-tuples without using Template Haskell, so to generalize this you will have to switch to lists.
ntuplesWithSum 1 s = [[s]]
ntuplesWithSum n s = concatMap (\i -> map (i:) (ntuplesWithSum (n-1) (s-i))) [1..s-n+1]
nums n = concatMap (ntuplesWithSum n) [n..]
Here's another solution, with probably another slightly different idea of "smallest". My order is just "all tuples with max element N come before all tuples with max element N+1". I wrote the versions for pairs and triples:
gen2_step :: Int -> [(Int, Int)]
gen2_step s = [(x, y) | x <- [1..s], y <- [1..s], (x == s || y == s)]
gen2 :: Int -> [(Int, Int)]
gen2 n = concatMap gen2_step [1..n]
gen2inf :: [(Int, Int)]
gen2inf = concatMap gen2_step [1..]
gen3_step :: Int -> [(Int, Int, Int)]
gen3_step s = [(x, y, z) | x <- [1..s], y <- [1..s], z <- [1..s], (x == s || y == s || z == s)]
gen3 :: Int -> [(Int, Int, Int)]
gen3 n = concatMap gen3_step [1..n]
gen3inf :: [(Int, Int, Int)]
gen3inf = concatMap gen3_step [1..]
You can't really generalize it to N-tuples, though as long as you stay homogeneous, you may be able to generalize it if you use arrays. But I don't want to tie my brain into that knot.
I think this is the simplest solution if "smallest" is defined as x+y+z because after you find your first solution in the space of Integral valued pythagorean triangles, your next solutions from the infinite list are bigger.
take 1 [(x,y,z) | y <- [1..], x <- [1..y], z <- [1..x], z*z + x*x == y*y]
-> [(4,5,3)]
It has the nice property that it returns each symmetrically unique solution only once. x and z are also infinite, because y is infinite.
This does not work, because the sequence for x never finishes, and thus you never get a value for y, not to mention z. The rightmost generator is the innermost loop.
take 1 [(z,y,x)|z <- [1..],y <- [1..],x <- [1..],x*x + y*y == z*z]
Sry, it's quite a while since I did haskell, so I'm going to describe it with words.
As I pointed out in my comment. It is not possible to find the smallest anything in an infinite list, since there could always be a smaller one.
What you can do is, have a stream based approach that takes the lists and returns a list with only 'valid' elements, i. e. where the condition is met. Lets call this function triangle
You can then compute the triangle list to some extent with take n (triangle ...) and from this n elements you can find the minium.
I'm totally new to Haskell so apologies if the question is silly.
What I want to do is recursively build a list while at the same time building up an accumulated value based on the recursive calls. This is for a problem I'm doing for a Coursera course, so I won't post the exact problem but something analogous.
Say for example I wanted to take a list of ints and double each one (ignoring for the purpose of the example that I could just use map), but I also wanted to count up how many times the number '5' appears in the list.
So to do the doubling I could do this:
foo [] = []
foo (x:xs) = x * 2 : foo xs
So far so easy. But how can I also maintain a count of how many times x is a five? The best solution I've got is to use an explicit accumulator like this, which I don't like as it reverses the list, so you need to do a reverse at the end:
foo total acc [] = (total, reverse acc)
foo total acc (x:xs) = foo (if x == 5 then total + 1 else total) (x*2 : acc) xs
But I feel like this should be able to be handled nicer by the State monad, which I haven't used before, but when I try to construct a function that will fit the pattern I've seen I get stuck because of the recursive call to foo. Is there a nicer way to do this?
EDIT: I need this to work for very long lists, so any recursive calls need to be tail-recursive too. (The example I have here manages to be tail-recursive thanks to Haskell's 'tail recursion modulo cons').
Using State monad it can be something like:
foo :: [Int] -> State Int [Int]
foo [] = return []
foo (x:xs) = do
i <- get
put $ if x==5 then (i+1) else i
r <- foo xs
return $ (x*2):r
main = do
let (lst,count) = runState (foo [1,2,5,6,5,5]) 0 in
putStr $ show count
This is a simple fold
foo :: [Integer] -> ([Integer], Int)
foo [] = ([], 0)
foo (x : xs) = let (rs, n) = foo xs
in (2 * x : rs, if x == 5 then n + 1 else n)
or expressed using foldr
foo' :: [Integer] -> ([Integer], Int)
foo' = foldr f ([], 0)
where
f x (rs, n) = (2 * x : rs, if x == 5 then n + 1 else n)
The accumulated value is a pair of both the operations.
Notes:
Have a look at Beautiful folding. It shows a nice way how to make such computations composable.
You can use State for the same thing as well, by viewing each element as a stateful computation. This is a bit overkill, but certainly possible. In fact, any fold can be expressed as a sequence of State computations:
import Control.Monad
import Control.Monad.State
-- I used a slightly non-standard signature for a left fold
-- for simplicity.
foldl' :: (b -> a -> a) -> a -> [b] -> a
foldl' f z xs = execState (mapM_ (modify . f) xs) z
Function mapM_ first maps each element of xs to a stateful computation by modify . f :: b -> State a (). Then it combines a list of such computations into one of type State a () (it discards the results of the monadic computations, just keeps the effects). Finally we run this stateful computation on z.