简体   繁体   English

haskell 减半函数

[英]haskell halve function

Using library functions, define a function halve :: [a ] → ([a ], [a ]) that splits an even-lengthed list into two halves.使用库函数,定义一个函数halve :: [a ] → ([a ], [a ]) 将偶数长度列表分成两半。 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.这是错误的,因为 xs -> take ((length x) div 2 ) xs 只显示列表的前半部分...请帮助我继续,以便它显示列表的后半部分。

I bumped into the same problem at Programming in Haskell from Graham Hutton.Graham Hutton 的Programming in Haskell 中遇到了同样的问题。 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曾经给我带来一些麻烦的小事是意识到我需要使用div而不是(/)因为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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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