用文件夹在haskell中实现插入 [英] Implement insert in haskell with foldr

查看:56
本文介绍了用文件夹在haskell中实现插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在haskell中使用文件夹实现插入. 我试过了:

How to implement insert using foldr in haskell. I tried:

insert'' :: Ord a => a -> [a] -> [a]
insert'' e xs = foldr (\x -> \y -> if x<y then x:y else y:x) [e] xs

没有骰子. 我必须在列表中插入元素e,以便它在大于或等于它的第一个元素之前出现.

No dice. I have to insert element e in list so that it goes before first element that is larger or equal to it.

示例:

insert'' 2.5 [1,2,3] => [1.0,2.0,2.5,3.0]
insert'' 2.5 [3,2,1] => [2.5,3.0,2.0,1.0]
insert'' 2 [1,2,1]   => [1,2,2,1]

在最后一个示例中,前2个插入了一个.

In last example first 2 is inserted one.

谢谢@李.

我现在有这个:

insert'' :: Ord a => a -> [a] -> [a]
insert'' e xs = insert2 e (reverse xs)
insert2 e = reverse .  snd . foldr (\i (done, l) -> if (done == False) && (vj e i) then (True, e:i:l) else (done, i:l)) (False, [])
    where vj e i = e<=i

但是这不起作用:

insert'' 2 [1,3,2,3,3] => [1,3,2,2,3,3]
insert'' 2 [1,3,3,4]   => [1,3,2,3,4]
insert'' 2 [4,3,2,1]   => [4,2,3,2,1]

解决方案:

insert'' :: Ord a => a -> [a] -> [a]
insert'' x xs = foldr pom poc xs False
  where
    pom y f je
      | je || x > y = y : f je
      | otherwise   = x : y : f True
    poc True = []
    poc _    = [x]

感谢@Pedro Rodrigues(它只是想将x> = y更改为x> y.)

Thanks @Pedro Rodrigues (It just nedded to change x>=y to x>y.)

(如何将其标记为已回答?)

(How to mark this as answered?)

推荐答案

这是我的看法:

insert :: Ord a => a -> [a] -> [a]
insert x xs = foldr aux initial xs False
  where
    aux y f done
      | done || x > y = y : f done
      | otherwise = x : y : f True
    initial True = []
    initial _ = [x]

但是,使用foldr的恕我直言不是最适合此问题的方法,对我来说,以下解决方案更容易理解:

However IMHO using foldr is not the best fit for this problem, and for me the following solution is easier to understand:

insert :: Int -> [Int] -> [Int]
insert x [] = [x]
insert x z@(y : ys)
  | x <= y = x : z
  | otherwise = y : insert x ys

这篇关于用文件夹在haskell中实现插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆