此代码中预期的Haskell逆函数是什么?

问题描述 投票:0回答:1

我正在写一个小的Haskell练习,应该在列表中移动某些元素,类似于Caesar密码,代码已经在工作,下面是代码。

module Lib (shift, cipherEncode, cipherDecode ) where
import Data.Char
import Data.List
import Data.Maybe

abcdata :: [Char]
abcdata = ['a','b','c','d','e','f','g']

iabcdata :: [Char]
iabcdata = ['g','f','e','d','c','b','a']

shift :: Char -> Int -> Char
shift l n = if (n >= 0)
            then normalShift l n
            else inverseShift l (abs n)

normalShift :: Char -> Int -> Char
normalShift l n = shifter l n abcdata

inverseShift :: Char -> Int -> Char
inverseShift l n = shifter l n reverse(abcdata) -- This is the line

charIdx :: Char -> [Char] -> Int
charIdx target xs = fromJust $ elemIndex target xs

shifter :: Char -> Int -> [Char] -> Char
shifter l n xs = if (n < length (xs))
            then
                picker ((charIdx l xs) + n) xs
            else
                picker ((charIdx l xs) + (n `mod` length (xs))) xs

picker :: Int -> [Char] -> Char
picker n xs = if n < length xs
              then
                xs!!n
              else
                xs!!(n `mod` length (xs))

我有关于电话的问题

inverseShift l n = shifter l n reverse(abcdata)

如果我用]进行更改>

inverseShift l n = shifter l n iabcdata

效果很好

而且,当我执行reverse(abcdata) == iabcdata时,它是True但是当我在代码中保留reverse时,出现以下错误

    * Couldn't match expected type `[Char] -> Char'
                  with actual type `Char'
    * The function `shifter' is applied to four arguments,
      but its type `Char -> Int -> [Char] -> Char' has only three
      In the expression: shifter l n reverse (abcdata)
      In an equation for `inverseShift':
          inverseShift l n = shifter l n reverse (abcdata)
   |
21 | inverseShift l n = shifter l n reverse(abcdata)
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    * Couldn't match expected type `[Char]'
                  with actual type `[a0] -> [a0]'
    * Probable cause: `reverse' is applied to too few arguments

[通过shifter调用reverse(abcdata)在做什么?

我正在写一个小的Haskell练习,应该在列表中移动某些元素,类似于Caesar密码,代码已经在工作,代码在下面。模块Lib(shift,cipherEncode,...

function haskell matching
1个回答
0
投票

括号在Haskell中不是这样的。您编写它的方式reverseabcdata都是shifter的参数,但是您希望abcdata作为reverse的参数。用shifter l n (reverse abcdata)代替shifter l n reverse(abcdata)

© www.soinside.com 2019 - 2024. All rights reserved.