如何删除Haskell列表中的第n个元素 [英] how do you delete the nth element in a list in Haskell

查看:60
本文介绍了如何删除Haskell列表中的第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写函数的实现,该函数采用数字n和列表,并从列表中删除位置n的元素.例如:删除0 [1、2、3、4] = [2、3、4]

How to write the implementation for the function which takes a number n and a list and removes the element at position n from the list. For example: remove 0 [1, 2, 3, 4] = [2, 3, 4]

这是我的尝试:

import Data.List.Split
remove :: Int -> [a] -> [a]
remove xs = let remove n xs = let (as, bs) = splitAt n xs in as ++ tail bs

但是它不起作用,并向我显示变量不在范围内" .有谁知道如何修理它?谢谢!

But it doesn't work and shows me "Variable not in scope". Does anyone know how to fix it? Appreciate!!

推荐答案

我写了一种非常直观的递归方法:

I wrote a pretty intuitive recursive approach:

remove :: Int -> [a] -> [a]
remove _ [] = []
remove 0 (x:xs) = xs
remove n (x:xs) = x : remove (n-1) (xs)

考虑到我正在考虑第一个元素为索引0.如果您有任何疑问,请告诉我.

Take into account that I am considering the first element to be index 0. Let me know if you have any doubts.

这篇关于如何删除Haskell列表中的第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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