简体   繁体   中英

haskell halve function

Using library functions, define a function halve :: [a ] → ([a ], [a ]) that splits an even-lengthed list into two halves. For example:

> halve [1, 2, 3, 4, 5, 6]
([1, 2, 3], [4, 5, 6])

so far what I have is

halve :: [a] -> ([a],[a])
halve = (\xs -> case xs of
        [] -> ([],[])
        xs -> take ((length xs) `div` 2 ) xs)

and it's wrong since xs -> take ((length x) div 2 ) xs only shows the first half of the list...please help me continue so that it will show the second half of the list.

I bumped into the same problem at Programming in Haskell from Graham Hutton. My solution was:

halve :: [a] -> ([a], [a]) 
halve xs = 
    ((take s xs), (drop s xs))
    where
        s = (length xs ) `div` 2

Once small thing that gave me some trouble was realising that I needed to use div instead of (/) since length :: Foldable t => ta -> Int and (/) :: Fractional a => a -> a -> a

thanks for commenting some solutions. I solved it...here it is

first_halve :: [a] -> [a]
first_halve = (\xs -> case xs of
            [] -> []
            xs -> take ((length xs) `div` 2 ) xs)

second_halve :: [a] -> [a]
second_halve = (\xs -> case xs of
            [] -> []
            xs -> drop ((length xs) `div` 2 ) xs)

halve :: [a] -> ([a],[a])
halve = (\xs -> case xs of
            [] -> ([],[])
            xs -> (first_halve xs, second_halve xs))
Hm... five years later and I'm probably working through the same text: 
Programming in Haskell 1st edition. Your question gave me the hint I 
needed to solve the problem:
halve :: [a] -> ([a], [a])
halve xs = (take l xs, drop l xs) 
           where l = div (length xs) 2 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM