Haskell Casting

a) I need to drop from Stringto intin haskell. I have a function that gets the third word in a sentence as a string, but my third word in all my sentences is numbers (int), how can I drop from a string to int, then use a number to do operations like add or multi?

getThirdWord :: String -> String
getThirdWord = head . tail . tail . words

b) I am using Visual Haskell Studio. How can I use functions such as mapand zipin visual haskell studio? Are there any plugins I need to include in my VHS to get them working?

Thank you so much in advance!

+3
source share
4 answers

Yacoby, , . :

  • read . String Int. . getThirdWord String -> Int, read , . , , - read, : Haskell .
  • head . tail . tail . , , , 23- ? (!!): . :

    thirdWordAsInt :: String -> Int 
    thirdWordAsInt = read . (!! 2) . words
    

    ( 2 3, 0.)

+14

, read.

getThirdWord :: String -> Int
getThirdWord = read . head . tail . tail . words

Visual Haskell Studio IDE , GHC, Haskell , .

+6

Yacoby read, , head/tail read . , head, . ,

get3rd :: String -> String
get3rd s =
  case (take 3 $ words s) of
    [_,_,w]   -> w
    otherwise -> ""

( , 3 ). , , , head/tail.

read ( ), reads :

toInt :: String -> Maybe Int
toInt s =
  case reads s of
    [(i,_)]   -> Just i
    otherwise -> Nothing

-- test cases
main = do
  print . toInt . get3rd $ "1 2 3"
  print . toInt . get3rd $ "one two three"
  print . toInt . get3rd $ "short list"

toInt Just Nothing, . readMay.

+3

, , , , , , , .

as :: (Read a, Show a) => (a -> a) -> String -> String
as f = show . f . read

Prelude> as (+1) "7"
"8"

Prelude> as (+(1/2)) "5"
"5.5"

, ? = . xs!! n xs n- . . ​​

0

Source: https://habr.com/ru/post/1724006/


All Articles