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
cuthave to return anErrorvalue? Or can you come up with a reasonable definition that works for all inputs. For example,taildoesn't work for all inputs, whereastakedoes. Investigatetakeand 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
dobothto do if the result of thecutis an error?Does
dobothoperate on elements of a list independently? Or are the result dependent on earlier computations? The first ismaplike, the secondfoldlike. You want to perform acutandmixfor each value in the[Int]input, but should the input tocutbe the original list, or the list from the previous step?Given that you have computed one step of
doboth, what should the next step ofdobothlook like? Try writing out the code that would do two, or even three, steps ofdobothat once.What is the value of
dobothif the[Int]argument is empty?
加载中,请稍侯......
精彩评论