Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community

    Hey, I am trying to deal with exceptions by converting them to strings. basically i want to do this:

    convertExceptionToString :: Exception e => IO (Either e a) -> IO (Either String a)
    convertExceptionToString arg = fmap convertExceptionToStringHelper arg
    convertExceptionToStringHelper :: Exception e => Either e a -> Either String a
    convertExceptionToStringHelper = either (Left . show) Right

    more background, i am getting these exceptions from things like this:

    import Network.HTTP.Simple
    try $ httpLBS request
    I get this sort of error when I try it:
    λ> stuff = try $ httpLBS (buildRequest myToken webHost "GET" hostApiPath)
    λ> convertExceptionToString stuff
    <interactive>:727:1-30: error:
        • Ambiguous type variable ‘e0’ arising from a use of ‘convertExceptionToString’
          prevents the constraint ‘(Exception e0)’ from being solved.
          Probable fix: use a type annotation to specify what ‘e0’ should be.
    my googling seems to indicate it is because of the buried show in my helper meaning the outer function still has to be aware of the exception type. but i have no idea how to fix it
    I think i got around it. i activated extension: TypeApplications and am doing this and it is working:
    λ> stuff = try @HttpException $ httpLBS (buildRequest myToken webHost "GET" hostApiPath)
    λ> :t convertExceptionToString stuff
    convertExceptionToString stuff
      :: IO (Either String (Response LC.ByteString))
    Sidiney Rodrigues

    Hello all! I'm trying to understand RankNTypes with this example https://stackoverflow.com/a/24717685
    but something does not work. Could anybody explain what the error is?

    {-# LANGUAGE RankNTypes #-}
    {-# LANGUAGE ImpredicativeTypes #-}
    module Main(main) where
    data Country = BigEnemy | MediumEnemy | PunyEnemy | TradePartner | Ally | BestAlly deriving Show
    f :: (forall a. Show a => [a] -> a) -> String
    f g = show $ g [BigEnemy, MediumEnemy, PunyEnemy]
    main = do
      print $ f (\_ -> BigEnemy)


    Main.hs:11:20: error:
        * Couldn't match expected type `a' with actual type `Country'
          `a' is a rigid type variable bound by
            a type expected by the context:
              forall a. Show a => [a] -> a
            at Main.hs:11:13-28
        * In the expression: BigEnemy
          In the first argument of `f', namely `(\ _ -> BigEnemy)'
          In the second argument of `($)', namely `f (\ _ -> BigEnemy)'
    11 |   print $ f (\_ -> BigEnemy)
       |                    ^^^^^^^^
    exit status 1
    Javier Figueroa
    main :: IO () main = do putStrLn "----------Menú Parser---------\n Choose an Option :\n\n1-Enter functional files.\n2-Enter Not functional files\n3-Salir del Programa.\n------------------------------" button <- getLine case button of "1" -> do putStrLn "----------Menú Parser---------\nChoose an Option:\n\n1-Run File funcionalTest1.\n2-Run File funcionalTest2.\n3-Run File funcionalTest3.\n4-Run File funcionalTest4.\n5-Run File funcionalTest5.\n6-Exit the program\n------------------------------" button2 <-getLine case button2 of "1" -> do parsed <- PP.parserFile $ "./foldertFunctional/funcionalTest1.lua" putStrLn $ show parsed "2" -> do parsed <- PP.parserFile $ "./foldertFunctional/funcionalTest2.lua" putStrLn $ show parsed "3" -> do parsed <- PP.parserFile $ "./foldertFunctional/funcionalTest3.lua" putStrLn $ show parsed "4" -> do parsed <- PP.parserFile $ "./foldertFunctional/funcionalTest4.lua" putStrLn $ show parsed "5" -> do parsed <- PP.parserFile $ "./foldertFunctional/funcionalTest5.lua" putStrLn $ show parsed "6" -> exitSuccess _ -> putStrLn "This option not exists" "2" -> do putStrLn "----------Menú Parser---------\nChoose an option:\n\n1-Run File noFuncionalTest1.\n2-Run File noFuncionalTest2.\n3-Run File noFuncionalTest3.\n4-Run File noFuncionalTest4.\n5-Run File noFuncionalTest5.\n6-Exit the program\n------------------------------" button2 <-getLine case button2 of "1" -> do parsed <- PP.parserFile $ "./folderNotFunctional/noFuncionalTest1.lua" putStrLn $ show parsed "2" -> do parsed <- PP.parserFile $ "./folderNotFunctional/noFuncionalTest2.lua" putStrLn $ show parsed "3" -> do parsed <- PP.parserFile $ "./folderNotFunctional/noFuncionalTest3.lua" putStrLn $ show parsed "4" -> do parsed <- PP.parserFile $ "./folderNotFunctional/noFuncionalTest4.lua" putStrLn $ show parsed "5" -> do parsed <- PP.parserFile $ "./folderNotFunctional/noFuncionalTest5.lua" putStrLn $ show parsed "6" -> exitSuccess _ -> putStrLn "This option not exists" "3" -> exitSuccess _ -> putStrLn "This option not exists"
    How can I improve this code? is there a simpler or shorter way?I help me?
    Chris Durden
    I lack expertise in this area, but my intuition suggests that Haskell would be an ideal language to write a computer algebra system. Am I wrong?
    Mihai Maruseac
    not wrong at all
    hello. im having trouble to understand a syntax i encountered in a snipper from the haskell wiki :
    primes = sieve [2..] where sieve (p:xs) = p : sieve [x | x <- xs, x mod p /= 0]
    in the where part, what does maen (p:xs) ? i understand that we are declaring a function called sieve, are p and xs related to sieve arguments ?
    ah found a more explicit example, it allows to get head and tail from a list
    Oliver Weichhold
    Could anyone explain to me what these three functions do?
    checkTarget :: Target -> Work -> IO Bool
    checkTarget t w = do
        t' <- powHashToTargetWords (powHash w)
        return $ targetFromWords t' <= t
    {-# INLINE checkTarget #-}
    powHashToTargetWords :: Digest Blake2s_256 -> IO TargetWords
    powHashToTargetWords h = BA.withByteArray h $ \ptr -> TargetWords
        <$> peekWord64OffLe ptr 0
        <*> peekWord64OffLe ptr 8
        <*> peekWord64OffLe ptr 16
        <*> peekWord64OffLe ptr 24
    {-# INLINE powHashToTargetWords #-}
    powHash :: Work -> Digest Blake2s_256
    powHash (Work bytes) = hash (BS.fromShort bytes)
    {-# INLINE powHash #-}
    Hi I have some queries in haskell can someone help me on personal chat ?

    Q)Write a Haskell program that:
    • reads a file called “filelist.txt ”, that contains a list of filenames, one per
    line (with no extra whitespace or other text).
    • For each filename “fname” in “filelist.txt ”, it writes a file with that
    name, whose contents are that filename, converted to uppercase. For
    example if filename “secret.log” appears in “filelist.txt ”, then a file
    called “secret.log” should be written, with contents “SECRET.LOG”.
    You can assume the names “filelist.txt ”, “FILELIST.TXT”, or any
    mixed-case versions of them, do not occur inside the “filelist.txt ” file

    My answers)

    fileToUpperCase =
    do text <- readFile ("filelist.txt")
    writeFile ("SECRET.log") (toUpper text)
    putStr "Done."

    Can you correct me?

    Hi how do I start contributing in open source?
    Alexander Babin

    Hi, smb know how to start "stack --ghci" into spacemacs
    i go to src/Lib.hs then SPC m s b - start repl but it start as a clear ghci without stack and load Lib.hs and dependencies

    spacemacs config part

         (haskell :variables haskell-process-type 'stack-ghci)
         ;; ----------------------------------------------------------------
         ;; Example of useful layers you may want to use right away.
         ;; Uncomment some layer names and press `SPC f e R' (Vim style) or
         ;; `M-m f e R' (Emacs style) to install them.
         ;; ----------------------------------------------------------------
         (auto-completion :variables
                          auto-completion-return-key-behavior 'complete
                          auto-completion-tab-key-behavior 'cycle
                          auto-completion-complete-with-key-sequence nil
                          auto-completion-complete-with-key-sequence-delay 0.1
                          auto-completion-minimum-prefix-length 2
                          auto-completion-idle-delay 0.2
                          auto-completion-private-snippets-directory nil
                          auto-completion-enable-snippets-in-popup nil
                          auto-completion-enable-help-tooltip nil
                          auto-completion-use-company-box nil
                          auto-completion-enable-sort-by-usage nil)
    fun:: Int -> (Int -> Int -> IO()) -> IO()
    fun n f = \a b -> f a b
    Why my code can not compile?
    could not figure out...
    How to write my function have above signature ?
    f is return a IO() , so f a b return a IO ()
    Mihai Maruseac
    your function has 4 arguments, but the type has 2
    Miko Chu
    i am trying to learn haskell, are there any tool to manage the version of my haskell and switch between versions?
    1 reply
    Jorge Martí Marín
    Hello everyone, I am starting my Haskell journey and want to do some experiments with networking with TLS... anyone knows about any tutorial/example/documentation related to using TLS in haskell?
    Ashkan Khanzadeh Nazary

    Hello everyone 👋 n00b here. How come this doesn't work :

    ashkan :: String -> IO ()
    ashkan c = do 
        where f = 
            return ()

    but the following does:

    ashkan :: String -> IO ()
    ashkan c = do 
        where f = do return ()
    zmijson vanset
    hello anyone on?
    Mihai Maruseac
    always ask the question directly and people will answer when they see it
    Normen Müller

    Monad transformers. The documentations says:

    A monad transformer makes a new monad out of an existing monad, such that computations of the old monad may be embedded in the new one.

    What is the new monad, the existing monad, and the old monad?

    In case of newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }:

    Is m the existing mondad, and Maybethe old monad? What is the new monad? MaybeT m?

    Mihai Maruseac
    yes to all
    Normen Müller
    @mihaimaruseac thx 🤙

    import Text.Read (readMaybe)

    data Note = A | B | C | D | E | F | G
    deriving (Show , Eq)

    data Octave = O1 | O2 | O3
    deriving (Show , Eq)

    data Pitch = Pitch Note Octave

    instance Show Pitch where
    show (Pitch a b) = show a ++ " " ++ tail (show b)

    toPitch :: String-> Maybe Pitch
    toPitch [] = Nothing
    toPitch (x:xs) = let mNote = readMaybe [x] :: Note
    mOctave = readMaybe xs :: Octave
    in case (mNote, mOctave) of
    (Just n, Just o) -> Just $ Pitch n o
    _ -> Nothing

    With the above code, I am encountering a issue:
    Couldn't match expected type ‘Note’ with actual type ‘Maybe a1’
    In the expression: readMaybe [x] :: Note
    In an equation for ‘mNote’: mNote = readMaybe [x] :: Note
    However, I am not sure why this error arises
    I am trying to read string such as "A1"
    Please have a look at my questions, thank you very much
    Mihai Maruseac
    readMaybe returns Maybe a (Maybe Note in this case)
    (also, please use back-ticks to properly format the code, markdown syntax, to make it readable)
    Yes, i understand it returns a Maybe Note, but i am not sure why it fails to compile.
    I have my problem solved! Thanks!
    Mihai Maruseac
    sorry, I was gone, you have readMaybe [x] :: Note when it should have been readMaybe [x] :: Maybe Note (or use @Note like in readMaybe @Note [x] -- needs TypeApplications extension)
    Alexander Ljungberg

    Hey guys. I've got a data type with a bunch of Maybe variables. They describe various properties of a database field, and initially every member is Nothing because the work to figure these bits out hasn't been done yet. The type is called DataRepresentation.

    Now a little later I want to pass an instance of DataRepresentation to a different function to actually use it, but at this stage one of the members has to be populated, or it's a programming error (there is some path where we forget to populate this particular field).

    So I'm wondering, is there some way to make like I don't know, a subclass of DataRepresentation which is identical to the normal DataRepresentation except one of the fields is no longer a Maybe, so to speak? Basically the goal is to get a compile time error if you try to pass in a DataRepresentation which hasn't been sufficiently configured.

    Like right now I'm just throwing an error/panic if the field is not Just <something> since it's a programming error. I feel like it would be nicer to not allow that situation at all though.

    Obviously I could create a second data type... so maybe the first is called IncompleteDataRepresentation and the second DataRepresentation and the function that fills in the fields takes the first and returns the second and everywhere I need the full thing I require the latter type. But I'm wondering if there are different options to do this "nicely". In particular because this data type is used as a member of another data type so I'd need to make an incomplete version of that data type too.

    I don't know, maybe this doesn't really make sense. Just checking if anything stands out to more experienced Haskell devs as "oh no, this is the idiomatic way to do this".

    Mihai Maruseac
    data Record parsedField1 parsedField2 = MkRecord  { field1 :: parsedField1, field2 :: parsedField2 }
    type UnparsedRecord = Record (Maybe Int) (Maybe String)
    type PartialRecord = Record Int (Maybe String)
    type FullRecord = Record Int String
    Alexander Ljungberg
    Oh very interesting. Thank you!
    mew, I'm reading a dependent type checking tutorial and stumbled over data Env = Nil | Define Env ~Val and was wandering what the tilde in a data type constructor means. Also where can I look such informations up? searching via google for tilde in an algebraic data type just gave me lots of results about tilde in pattern matching and tilde for type equality.
    ah, it's a lazy data type for haskell Strict pragma
    The idea is to turn Haskell into a strict-by default language for a given module, with opt-in laziness for types defined in that module
    Mihai Maruseac
    yes, ~ is used to signal lazyness, same as ! is used for eagerness/strictness
    f ~(x:xs) = undefined
    g (x:xs) = undefined
    These 2 behave differently when called on empty list