[英]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.