[英]Haskell: Problem with making my own data-type be part of the Eq-typeclass
[英]Making my own data type “Cipher” in Haskell
我試圖在Haskell中創建自己的數據類型“ Cipher”。 我意識到有26個! 值可以接受的值(字母中字符的任何組合只能使用一次,也只能使用一次)。
我是這樣開始的:
數據密碼= ['a'..'z'] |
我知道Haskell可以“猜測”組合,但是如何告訴我我希望該類型能夠采用上述任何值?
一個簡單的答案可能是
import Data.Char (ord)
import Data.List (permutations)
newtype Cipher = Cipher String
ciphers = map Cipher . permutations $ ['a' .. 'z']
-- Lookup a characters value in the cipher
mapChar :: Cipher -> Char -> Char
mapChar ciph c = ciph !! ord c - ord 'a'
encode :: Cipher -> String -> String
encode ciph = map (mapChar ciph)
decode :: Cipher -> String -> String
decode -- Ill let you figure this out
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.