开发者

applying my functions?

开发者 https://www.devze.com 2023-02-20 04:07 出处:网络
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)

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 an Error value? Or can you come up with a reasonable definition that works for all inputs. For example, tail doesn't work for all inputs, whereas take does. Investigate take and see how it handles exceptional inputs. This might lead you to a better definition of cut. 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 the cut is an error?

  • Does doboth operate on elements of a list independently? Or are the result dependent on earlier computations? The first is map like, the second fold like. You want to perform a cut and mix for each value in the [Int] input, but should the input to cut 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 of doboth look like? Try writing out the code that would do two, or even three, steps of doboth at once.

  • What is the value of doboth if the [Int] argument is empty?

0

精彩评论

暂无评论...
验证码 换一张
取 消