Haskell - 过滤最后一个元素 [英] Haskell - Filter Last Element

查看:98
本文介绍了Haskell - 过滤最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想过滤不满足属性的列表的最后一个元素。一个例子是:

I want to filter the last element of a list that does not satisfy a property. An example would be

smallerOne :: a->Bool 
smallerOne x = x < 1 

函数filterLast应给出

The function filterLast should give

filterLast smallerOne [1, -2, -3, -4, 5] 
[1, -2, -3, -4] //Filters the last element that is not smaller than 1 

这里是我的代码(我是一个初学者,非常抱歉, p>

Here is my code (I am a beginner so sorry for the bad attempt)

filterLast :: (a -> Bool) -> [a] -> [a] 
filterLast p [] = [] 
filterLast p xs 
    | p (last xs) = filterLast p (init xs) : last xs 
    | otherwise = init xs 

感谢您的帮助

Thank you for your help

推荐答案

smallerOne :: (Ord a, Num a) => a -> Bool 
smallerOne x = x < 1 

filterLast :: (a -> Bool) -> [a] -> [a]
filterLast p (x:[]) = if (p x) then x:[] else []
filterLast p (x:xs) = x : filterLast p xs

这是解决您的问题的方法。现在,还有一些解释:

This is the solution to your problem. Now, also some explanation:


smallerOne ::(Ord a,Num a)=> a - > Bool

smallerOne :: (Ord a, Num a) => a -> Bool

您必须包含类别约束 Ord Num < 比较运算符来处理数字。你可以在这里阅读更多: http://learnyouahaskell.com/types-and-typeclasses#typeclasses -101

you must include the class constraint Ord and Num, because your are trying to ordonate numbers through this < comparison operator. You can read more here: http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101

filterLast 通过模式匹配实现,Haskell非常聪明,并且会进入与给定列表匹配的分支,因此他将进入该分支:

filterLast is implemented through pattern matching, Haskell is pretty smart and will enter the branch that will match the given list, so he will enter this branch:


filterLast仅当有一个元素时,p(x:[])= if(px)then x:[] else []

filterLast p (x:[]) = if (p x) then x:[] else []

,即你的最后一个元素

你说你是初学者,我真的推荐你这个教程, http://learnyouahaskell.com/chapters ,它非常酷。

You said you are a beginner, I really recommend you this tutorial, http://learnyouahaskell.com/chapters, it is pretty cool.

这篇关于Haskell - 过滤最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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