I made these two haskell functions,
cut :: Int -> [a] -> (Error ([a],[a]))
cut _ [] = Ok([],[])
cut n xs | n>0 && n < length xs = Ok(take n xs, drop n xs)
| n > length xs = error("Fail")
mix :: [a] -> [a] -> [a]
mix xs [] = xs
mix [] ys = ys
mix (x:xs) (y:ys) = x:y:mix xs ys
An now wish to make anouther funct开发者_如何学Goion in which i can use both of these,
this is what i have;
doboth :: [Int] -> [a] -> Error [a]
doboth (x:xs) list = mix((cut x list)) then send xs back to doboth recursivly for the next x elemet of the list.
The idea of this function is to cut a list and then mix the two lists, it gets the cut points from the do both list of ints...
ANy ideas?
Since cut returns not a list, you need to pattern match a bit:
case cut x list of
Ok (as, bs) -> mix ... ... -- and so forth
Shouldn't doboth return Error [[a]]?
Maybe you should use a standard type like Maybe or Either instead Error.
If I understand what you want correctly, then doboth would be something like
doboth xs list = mapM (\ x -> mix (cut x list)) xs
Assuming you've made Error into a monad (which Maybe and Either already are).
There are several questions you have to ask yourself:
Does
cut
have to return anError
value? Or can you come up with a reasonable definition that works for all inputs. For example,tail
doesn't work for all inputs, whereastake
does. Investigatetake
and see how it handles exceptional inputs. This might lead you to a better definition ofcut
. The reason this is important is that functions that return uniform results for all values are generally much easier to work with.What do you expect
doboth
to do if the result of thecut
is an error?Does
doboth
operate on elements of a list independently? Or are the result dependent on earlier computations? The first ismap
like, the secondfold
like. You want to perform acut
andmix
for each value in the[Int]
input, but should the input tocut
be the original list, or the list from the previous step?Given that you have computed one step of
doboth
, what should the next step ofdoboth
look like? Try writing out the code that would do two, or even three, steps ofdoboth
at once.What is the value of
doboth
if the[Int]
argument is empty?
精彩评论