如何推广代码?

时间:2017-06-13 09:15:00

标签: haskell

我正在学习haskell并按照功能写作练习:

  cipherCeasar :: Char -> Int -> Char
  cipherCeasar c i
    | isUpper c = chr (isBiggerMax ((+) i $ ord c) (ord 'A') (ord 'Z'))                    
    | otherwise = chr (isBiggerMax ((+) i $ ord c) (ord 'a') (ord 'z'))

正如您所看到的,守卫后的两行代码几乎相同 我如何概括代码或者它是否可以呢?

1 个答案:

答案 0 :(得分:4)

您可以使用辅助功能:

cipherCeasar :: Char -> Int -> Char
cipherCeasar c i
  | isUpper c = cipherBetween 'A' 'Z'
  | otherwise = cipherBetween 'a' 'z'
  where cipherBetween min max = chr (isBiggerMax ((+) i $ ord c) (ord min) (ord max))