简体   繁体   中英

Can someone explain this line of code in Haskell

So i have this program, it finds lowercase letters and turns them to uppercase. It works but can someone just explain what the code after the else statement does.

raise :: String -> String
raise xs =
    [x | char <- xs
     , char `elem` (['a'..'z'] ++ ['A'..'Z'] ++ ['0' .. '9'])
     , let x = if char `elem` ['A'..'Z'] ++ ['0' .. '9'] 
               then char
               else ['A'..'Z'] !! head [i | (i, x) <- zip [0..] ['a'..'z']
                                          , x == char]]

you can try it yourself in ghci (type 'ghci' or 'stack ghci' from a command line, depending on how you've installed Haskell, or even use one of those 'try haskell online' services)!

> let f char = ['A'..'Z'] !! head [i | (i, x) <- zip [0..] ['a'..'z'], x == char]
> f 'x'
'X'
> f '3'
{Prelude.head empty list error}

What does the part in the list do? Let's try it out!

> let f char = [i | (i, x) <- zip [0..] ['a'..'z'], x == char]
> f 'b'
[2]
> f '3'
[]

See how you can use ghci to figure out what a function does? Need help figuring out what arguments to add to f? Consider this:

> let f = [i | (i, x) <- zip [0..] ['a'..'z'], x == char]
{not in scope error: char}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM