排列一个符号回来,哈斯克尔 [英] Permutations one symbol back, Haskell

查看:90
本文介绍了排列一个符号回来,哈斯克尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让一个符号重新排列。我有一个给定的字符串: abcdpqrs ,其中输出将是: badcqpsr



我现在的代码:

  fs = foldr(\ a〜(x,y) - > (a:y,x))([],[])s 

main :: IO()
main = do
str < - getLine
print(f str)

评估 fabcdpqrs结果

 (acpr,
bdqs)

如何获得badcqpsr






更新的代码:

  rev(a :b:xs)= b:a:rev xs 
rev xs = xs
main = do
n< - getLine
l< - getContents
putStr(rev l)

当输入为2个字符串时, abcdpqrs az 结果是 badcqpsra z 。预期的输出是 badcqpsr za

解决方案

这是一个提示:

  reverseFirst2 :: [a]  - > [a] 
reverseFirst2(x1:x2:xs)= x2:x1:xs
reverseFirst2 xs = xs

这颠倒了列表的前2个元素的顺序。 reverseFirst2abcdpqrs
bacdpqrs

您可以填写 ... 下面做同样的事情到列表的其余部分?

  reverseEvery2: :[a]  - > [a] 
reverseEvery2(x1:x2:xs)= x2:x1:...
reverseEvery2 xs = xs



获取输入



要一次输入一行,请一次读取一行内容。

  main = do 
l < - getLine
print(reverseEvery2 l)
main

使用 getContents 得到该行为的原因是从 getContents 在行尾包含换行符。它基本上正在运行

  revabcdpqrs\\\
az\\\
=
badcqpsra\\\
\ nz


How I can permute one symbol back. I have a given string: abcdpqrs, where output will be: badcqpsr.

My current code:

f s = foldr (\a ~(x,y) -> (a:y,x)) ([],[]) s

main :: IO ()
main = do 
    str <- getLine
    print(f str)

Evaluating f "abcdpqrs" results in

("acpr",
 "bdqs")

How can this be used to get "badcqpsr"?


Updated code:

rev (a : b : xs) = b : a : rev xs
rev xs = xs
main = do
    n <- getLine
    l <- getContents
    putStr (rev l)

When input are 2 strings, abcdpqrs and az result is badcqpsra and z. Expected output is badcqpsr and za. How I can fix it?

解决方案

Here's a hint:

reverseFirst2 :: [a] -> [a]
reverseFirst2 (x1:x2:xs) = x2:x1:xs
reverseFirst2 xs = xs

This reverses the order of the first 2 elements of a list

> reverseFirst2 "abcdpqrs"
"bacdpqrs"

Can you fill in the ... below to do the same thing to the remainder of the list?

reverseEvery2 :: [a] -> [a]
reverseEvery2 (x1:x2:xs) = x2:x1: ...
reverseEvery2 xs = xs

Getting input

To get input one line at a time, read the input one line at a time.

main = do
    l <- getLine
    print (reverseEvery2 l)
    main

The reason you are getting that behavior with getContents is the input read from getContents includes the newline characters at the end of the lines. It is essentially running

rev "abcdpqrs\naz\n" =
    "badcqpsra\n\nz"

这篇关于排列一个符号回来,哈斯克尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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