Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

Retrieve value from tuple by giving number or letter in Haskell

I am very new to Haskell and am trying to retrieve 'a' if I give 0, 'b' if I give 1 and so on...

This is my code so far:

alpha = ['a'..'z']
numb = [0..25]

zippedChars = zip alpha numb

and this is the list: enter image description here

I want to make something like: getCharfromNumb, and if I type getCharfromNumb 0 I should receive 'a'. And getNumbfromChar 'a' should give me 0.

question from:https://stackoverflow.com/questions/65904330/retrieve-value-from-tuple-by-giving-number-or-letter-in-haskell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import Data.List
import Data.Tuple

getCharFromNum :: Int -> Maybe Char
getCharFromNum n = lookup n $ swap <$> zippedChars

getNumFromChar :: Char -> Maybe Int
getNumFromChar c = lookup c zippedChars

See Data.List.lookup, Data.Tuple.swap, and Data.Functor.<$>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...