繁体   English   中英

haskell 减半函数

[英]haskell halve function

使用库函数,定义一个函数halve :: [a ] → ([a ], [a ]) 将偶数长度列表分成两半。 例如:

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

到目前为止我所拥有的是

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

这是错误的,因为 xs -> take ((length x) div 2 ) xs 只显示列表的前半部分...请帮助我继续,以便它显示列表的后半部分。

Graham Hutton 的Programming in Haskell 中遇到了同样的问题。 我的解决方案是:

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

曾经给我带来一些麻烦的小事是意识到我需要使用div而不是(/)因为length :: Foldable t => ta -> Int and (/) :: Fractional a => a -> a -> a

感谢您评论一些解决方案。 我解决了……在这里

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