Haskell合并排序

编程入门 行业动态 更新时间:2024-10-27 00:28:54
本文介绍了Haskell合并排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是Mergesort的实现,它使用更高阶的函数,保护,where和递归.

This is an implementation of Mergesort using higher order functions,guards,where and recursion.

但是从编译器 6:26收到错误:解析输入"="

mergeSort :: ([a] -> [a] -> [a]) -> [a] -> [a] mergeSort merge xs | length xs < 2 = xs | otherwise = merge (mergeSort merge first) (mergeSort merge second) where first = take half xs second = drop half xs half = (length xs) `div` 2

我看不到有什么问题吗?甚至我不了解编译器.

I can't see whats wrong? or rather I don't understand the compiler.

推荐答案

将列表减半不是O(1)操作,而是O(n),因此与命令式合并排序相比,给定的解决方案会带来额外的成本.避免减半的一种方法是简单地通过制作单例直接开始合并,然后合并每两个连续的列表:

Halving a list is not an O(1) operation but O(n), so the given solutions introduce additional costs compared to the imperative version of merge sort. One way to avoid halving is to simply start merging directly by making singletons and then merging every two consecutive lists:

sort :: (Ord a) => [a] -> [a] sort = mergeAll . map (:[]) where mergeAll [] = [] mergeAll [t] = t mergeAll xs = mergeAll (mergePairs xs) mergePairs (x:y:xs) = merge x y:mergePairs xs mergePairs xs = xs

其中 merge 已由其他人指定.

更多推荐

Haskell合并排序

本文发布于:2023-11-30 17:07:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!