在列表上映射时如何考虑以前的元素? [英] How to consider previous elements when mapping over a list?

查看:85
本文介绍了在列表上映射时如何考虑以前的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



对于列表中的每个整数,检查前面有多少个整数是较小。

  smallerOnes [1,2,3,5]将会得到结果[(1,0),(2, 1),(3,2),(5,3)] 

目前我有:

  smallerOnes :: [Int]  - > [(Int,Int)] 
smallOnes [] = []
smallOnes(x:xs)=

我不知道如何解决这个问题。递归可能是在这里思考的方式,但在这一点上,我失去了它。

 import Data.List(inits)
smallOnes :: [Int] - > [(Int,Int)]
smallOnes xs = zipWith(\ x ys - >(x,length $ filter(< x)ys))xs(inits xs)


I'm stuck at making a function in Haskell wich has to do the following:

For each integer in a list check how many integers in front of it are smaller.

smallerOnes [1,2,3,5] will have the result [(1,0), (2,1), (3,2), (5,3)]

At the moment I have:

smallerOnes :: [Int] -> [(Int,Int)]
smallerOnes [] = []
smallerOnes (x:xs) =  

I don't have any clue on how to tackle this problem. Recursion is probably the way of thinking here but at that point I'm losing it.

解决方案

import Data.List (inits)
smallerOnes :: [Int] -> [(Int,Int)]
smallerOnes xs = zipWith (\x ys -> (x, length $ filter (< x) ys)) xs (inits xs)

这篇关于在列表上映射时如何考虑以前的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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