Haskell中的旋转功能 [英] Rotate function in Haskell

查看:67
本文介绍了Haskell中的旋转功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Haskell中编写一个函数,该函数将由第二个参数给出的列表旋转第一个参数指示的位置数.使用模式匹配,实现递归函数

I want to write a function in Haskell that rotates the list given as the second argument by the number of positions indicated by the first argument. Using pattern matching, implement a recursive function

我编写了以下函数:

rotate :: Int -> [a] -> [a]
rotate 0 [y]= [y]
rotate x [y]= rotate((x-1) [tail [y] ++ head [y]])

,但是此函数始终会产生错误.有什么办法解决吗?该函数在运行时应执行以下操作:

but this function always produces a error. Is there any way to solve it? The function should do the following when it runs:

rotate 1 "abcdef"
"bcdefa"

推荐答案

[y] 并不意味着让 y 成为列表".这意味着此参数是一个包含一个名为 y 的元素的列表".您拥有正确的结构,但不需要 y 周围的括号.

[y] does not mean "let y be a list". It means "this argument is a list containing one element called y". You have the right structure, but you don't need the brackets around the y.

rotate :: Int -> [a] -> [a]
rotate 0 y = y
rotate x y = rotate (x-1) (tail y ++ [head y])

这篇关于Haskell中的旋转功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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