VegOwOtenks

joined 2 years ago
[–] VegOwOtenks@lemmy.world 2 points 1 day ago (1 children)

Thank you for this update. Now that problwm and solution fit, I can understand whats going on in your code :]

[–] VegOwOtenks@lemmy.world 2 points 3 days ago

I was scared of a hard combinatorial puzzle day, but this was a breeze.

{-# LANGUAGE TupleSections #-}
module Main (main) where
import Control.Monad ((<$!>))
import qualified Data.Text.IO as TextIO
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.IntSet as IntSet
import Control.Arrow ((>>>))
import qualified Data.List as List
import qualified Data.IntMap as IntMap

part1 :: [IntSet.Key] -> IntSet.Key
part1 = IntSet.fromList
  >>> IntSet.foldl (+) 0

part2 :: [IntSet.Key] -> IntSet.Key
part2 = IntSet.fromList
  >>> IntSet.toAscList
  >>> take 20
  >>> sum

part3 :: [IntMap.Key] -> Int
part3 = List.map (, 1)
  >>> IntMap.fromListWith (+)
  >>> IntMap.toList
  >>> List.map snd
  >>> maximum

main :: IO ()
main = do
  sizes <- map (read . Text.unpack) . Text.split (== ',') <$!> TextIO.getLine
  print $ part1 sizes
  print $ part2 sizes
  print $ part3 sizes
 

For debugging purposes, we had the program print dots and Xs to see where we went wrong. This is from the output of my girlfriends python script.

I converted this from the text-based output of her program in day two. First to a portable anymap (nmp) and then I used GIMP to produce a gif.

[–] VegOwOtenks@lemmy.world 3 points 3 days ago* (last edited 3 days ago)

I struggled for a long time because I had nearly the correct results. I had to switch div with quot.

This puzzle was fun. If you have a visualization, it's even cooler. (It's a fractal)

Haskell Code

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternSynonyms #-}
{-# OPTIONS_GHC -Wall #-}
module Main (main) where
import Text.Read (ReadPrec, Read (readPrec))
import Data.Functor ((<&>))
import Data.Text (pattern (:<), Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as TextIO
import Control.Monad ((<$!>))
import Control.Arrow ((<<<))

newtype Complex = Complex (Int, Int)

instance Read Complex where
  readPrec :: ReadPrec Complex
  readPrec = readPrec <&> \case
    [a, b] -> Complex (a, b)
    _ -> undefined

instance Show Complex where
  show :: Complex -> String
  show (Complex (a, b))= show [a, b]

readAEquals :: Text -> Complex
readAEquals ('A' :< '=':< rest) = read $ Text.unpack rest
readAEquals _ = undefined


-- >>> Complex (1, 1) `add` Complex (2, 2)
-- [3,3]

add :: Complex -> Complex -> Complex
(Complex (x1, y1)) `add` (Complex (x2, y2)) = Complex (x1 + x2, y1 + y2)

-- >>> Complex (2, 5) `times` Complex (5, 7)
-- [-25,-11]

times :: Complex -> Complex -> Complex
(Complex (x1, y1)) `times` (Complex (x2, y2)) = Complex (x1 * x2 - y1 * y2, x1 * y2 + x2 * y1)

dividedBy :: Complex -> Complex -> Complex
(Complex (x1, y1)) `dividedBy` (Complex (x2, y2)) = Complex (x1 `quot` x2, y1 `quot` y2)

step :: Complex -> Complex -> Complex
step a r = let
 r1 = r `times` r
 r2 = r1 `dividedBy` Complex (10, 10)
 r3 = r2 `add` a
 in r3

zero :: Complex
zero = Complex (0, 0)

part1 :: Complex -> Complex
part1 a = iterate (step a) (Complex (0, 0)) !! 3

shouldBeEngraved :: Complex -> Bool
shouldBeEngraved complexPoint = let

  cycleStep :: Complex -> Complex -> Complex
  cycleStep point r = let
    r2 = r `times` r
    r3 = r2 `dividedBy` Complex (100000, 100000)
    in point `add` r3

  inRange x = x <= 1000000 && x >= -1000000


  in all (\ (Complex (x, y)) -> inRange x && inRange y)
    <<< take 101
    <<< iterate (cycleStep complexPoint)
    $ zero

-- >>> shouldBeEngraved $ Complex (35630,-64880)
-- True
-- >>> shouldBeEngraved $ Complex (35460, -64910)
-- False
-- >>> shouldBeEngraved $ Complex (35630, -64830)
-- False

part2 :: Complex -> Int
part2 (Complex (xA, yA)) = let

    xB = xA + 1000
    yB = yA + 1000

  in length . filter shouldBeEngraved $ do
    x <- [xA, xA+10.. xB]
    y <- [yA, yA+10.. yB]
    pure $ Complex (x, y)

part3 :: Complex -> Int
part3 (Complex (xA, yA)) = length . filter shouldBeEngraved $ do
  x <- [xA..xA+1000]
  y <- [yA..yA+1000]
  pure $ Complex (x, y)

-- >>> [0, 10..100]
-- [0,10,20,30,40,50,60,70,80,90,100]

main :: IO ()
main = do
  a <- readAEquals <$!> TextIO.getContents
  print $ part1 a
  print $ part2 a
  print $ part3 a

My girlfriend is learning python, we are taking on the challenges together, today I may upload her solution:

python

A=[-3344,68783]
R = [0, 0]
B= [A[0]+1000, A[1]+1000]
pointsengraved = 0
cycleright = 0


for i in range(A[1], B[1]+1):
    for j in range(A[0], B[0]+1):
        for k in range(100):
            R = [int(R[0] * R[0] - R[1] * R[1]), int(R[0] * R[1] + R[1] * R[0])]
            R = [int(R[0] / 100000), int(R[1] / 100000)]
            R = [int(R[0] + j), int(R[1] + i)]
            if -1000000>R[0] or R[0]>1000000 or -1000000>R[1] or R[1]>1000000:
                #print(".", end="")
                break
            cycleright += 1
        if cycleright == 100:
            pointsengraved += 1
            #print("+", end="")
        cycleright = 0
        R = [0, 0]
    #print()

print(pointsengraved)

The commented out print statements produce an ascii map of the set, which can be cool to view at the right font size.

[–] VegOwOtenks@lemmy.world 2 points 6 days ago

I'm very curious about F# since I've never used it or seen it anywhere before but I'm afraid I'm too tired to read it right now. Thank you for posting, I hope I'll remember to come back tomorrow.

[–] VegOwOtenks@lemmy.world 2 points 6 days ago

I coded this along with my girlfriend who's learning python, but not motivated to share her solution. The program reads from stdin, because I usually invoke it like so: runhaskell Main.hs < input or runhaskell Main.hs < example. I think this is quite handy because I don't have to change the source code to check the example input again.

I struggled with Part 3, where I suddenly forgot I could've simply used mod, which I ended up doing anyway. I immediately recognized that Part 3 needs Mutable Arrays if I care to avoid Index hell, which is not what I wanted to with Haskell but oh well.

{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE PatternSynonyms #-}
module Main (main) where

import qualified Data.Text as Text
import qualified Data.Text.IO as TextIO
import Control.Monad ((<$!>), forM_)
import Data.Text (Text, pattern (:<))
import qualified Data.List as List
import qualified Data.Array.MArray as MutableArray
import Control.Monad.ST (runST, ST)
import Data.Array.ST (STArray)

commaSepLine :: IO [Text.Text]
commaSepLine = Text.split (== ',') <$!> TextIO.getLine

readInstruction :: Text -> Int
readInstruction ('R' :< n) = read . Text.unpack $ n
readInstruction ('L' :< n) = negate . read . Text.unpack $ n
readInstruction _ = undefined

myName :: (Foldable t, Ord b, Enum b, Num b) => b -> t b -> b
myName maxPosition = List.foldl' (\ pos offset -> min (pred maxPosition) . max 0 $ pos + offset) 0

parentName1 :: [Int] -> Int
parentName1 = List.sum

newSTArray :: [e] -> ST s (STArray s Int e)
newSTArray xs = MutableArray.newListArray (0, length xs - 1) xs

swap :: (MutableArray.MArray a e m, MutableArray.Ix i) => a i e -> i -> i -> m ()
swap array i0 i1 = do
  e0 <- MutableArray.readArray array i0
  e1 <- MutableArray.readArray array i1
  MutableArray.writeArray array i0 e1
  MutableArray.writeArray array i1 e0

parentName2 :: [Text] -> [Int] -> Text
parentName2 nameList instructions = runST $ do
  names <- newSTArray nameList
  arrayLength <- succ . snd <$> MutableArray.getBounds names
  forM_ instructions $ \ offset -> do
    let arrayOffset = offset `mod` arrayLength
    swap names 0 arrayOffset
  MutableArray.readArray names 0

main :: IO ()
main = do
  names <- commaSepLine
  _ <- TextIO.getLine
  instructions <- fmap readInstruction <$> commaSepLine

  let namesLength = length names
  print $ names !! myName namesLength instructions
  print . (names !!) . (`mod` namesLength) $ parentName1 instructions
  print $ parentName2 names instructions
[–] VegOwOtenks@lemmy.world 5 points 2 weeks ago

Yes exactly that. It was previously called Coq, maybe you know it under that name?

https://rocq-prover.org/

[–] VegOwOtenks@lemmy.world 4 points 2 weeks ago

Somewhat, I'm quite motivated but it's part of my studies.

 

I'm learning to use Rocq, I felt very powerful.

[–] VegOwOtenks@lemmy.world 9 points 3 weeks ago (1 children)

Briesiges Wetter ist die beste Wetter-App, Γ€ndere meinen Verstand.

[–] VegOwOtenks@lemmy.world 3 points 4 months ago

I think this is what they are referring to: https://en.wikipedia.org/wiki/Broughton_Suspension_Bridge.

TL;DR: The bridge collapsed because soldiers marching on it created force they hadn't anticipated, soldiers breaking step supposedly don't have as much of an impact.

 

Dear @Noughtmare@programming.dev, I want to thank you for your weekly post, I'm always happy to find a haskell newsletter in my inbox.
I hope you're not inconvenienced by me posting the newsletter link this week. I was looking for it and figured others might be doing the same, hence why I posted it.

[–] VegOwOtenks@lemmy.world 7 points 7 months ago (1 children)

I also like watching Doctor Who, how did you manage to make a cute dalek? :d

[–] VegOwOtenks@lemmy.world 3 points 7 months ago (1 children)

The extension is called Burn-My-Windows and I always look forward to it when booting into GNOME because it feels so ✨fancy✨

[–] VegOwOtenks@lemmy.world 1 points 7 months ago

I stumbled over Gradience just yesterday but I tought it was archived sometime last year, is it still working accordingly?

 
 

I consider myself to be learning haskell. I am proficient enough to solve Advent of Code and do some small projects using it. I love doing it but I always feel like there's more to it. Apparently there is: this blog post from Reasonably Polymorphic caught me, I was probably exactly the intended audience.

What's in the blog post?

They visualize the Builder Pattern, where an Object is created through repeated mutation, which, when transferred to Haskell, should be replaced by creating objects through Monoids and the corresponding Semigroup function <>.

I parse a programming language using parsec and I did exactly what was proposed to enhance my structure creation.

Before, my code was this

Old Code

data StructStatement = Variable VariableName VariableType
        | Function Function.Function

data Struct = Struct 
        { name :: String
        , variables :: [(VariableName, VariableType)]
        , functions :: [Function]
        }
        deriving (Show)

addVariable :: Struct -> VariableName -> VariableType -> Struct
addVariable (Struct sn vs fs) n t = Struct sn ((n, t): vs) fs

addFunction :: Struct -> Function -> Struct
addFunction (Struct sn vs fs) f = Struct sn vs (f:fs)

accumulateStruct :: Struct -> StructStatement -> Struct
accumulateStruct s (Variable n t) = addVariable s n t
accumulateStruct s (Function f)   = addFunction s f

Then using a fold over Struct _ [] [] (which is basically mempty I just realized) would get me the complete struct. It is kind of ugly:

foldl accumulateStruct (Struct structIdentifier [] []) <$!> braces (many structMember)

Now my code is this

New Code

data Struct = Struct
        { name :: String
        , body :: StructBody
        }
        deriving (Show)

data StructBody = StructBody
        { variables :: [(VariableName, VariableType)]
        , functions :: [Function]
        }
        deriving stock (Generic, Show)
        deriving (Semigroup, Monoid) via Generically StructBody

Which shorter and easier to use, the entire construction only looks like this now:

mconcat <$!> UbcLanguage.braces (many structMember)

I love the new construction method using Semigroup and Monoid. However, I don't understand them in depth anymore. I have written my own instance of Semigroup and Monoid, and I assume these deriving clauses do something similar.

Handwritten Semigroup instance

instance Semigroup StructBody where
  (<>) s1 s2 = StructBody
        { variables = variables s1 <> variables s2
        , functions = functions s1 <> functions s2
        }

Monoid instance is trivial then, just default all the values to mempty.

I also have a dump of the generated class instances using -ddump-deriv -dsuppress-all:

Generated instances

instance Semigroup StructBody where
  (<>) :: StructBody -> StructBody -> StructBody
  sconcat :: NonEmpty StructBody -> StructBody
  stimes ::
    forall (b_a87f :: *). Integral b_a87f =>
                          b_a87f -> StructBody -> StructBody
  (<>)
    = coerce
        @(Generically StructBody
          -> Generically StructBody -> Generically StructBody)
        @(StructBody -> StructBody -> StructBody)
        ((<>) @(Generically StructBody))
  sconcat
    = coerce
        @(NonEmpty (Generically StructBody) -> Generically StructBody)
        @(NonEmpty StructBody -> StructBody)
        (sconcat @(Generically StructBody))
  stimes
    = coerce
        @(b_a87f -> Generically StructBody -> Generically StructBody)
        @(b_a87f -> StructBody -> StructBody)
        (stimes @(Generically StructBody))

instance Monoid StructBody where
  mempty :: StructBody
  mappend :: StructBody -> StructBody -> StructBody
  mconcat :: [StructBody] -> StructBody
  mempty
    = coerce
        @(Generically StructBody) @StructBody
        (mempty @(Generically StructBody))
  mappend
    = coerce
        @(Generically StructBody
          -> Generically StructBody -> Generically StructBody)
        @(StructBody -> StructBody -> StructBody)
        (mappend @(Generically StructBody))
  mconcat
    = coerce
        @([Generically StructBody] -> Generically StructBody)
        @([StructBody] -> StructBody) (mconcat @(Generically StructBody))

In the documentation it says that there is an instance (Generic a, Monoid (Rep a ())) => Monoid (Generically a) which is defined exactly like the generated instance ghc dumped (source) which uses the Monoid of (Rep a ()) which isn't defined anywhere.

Where does the monoid come from? This is the generated type Rep

Generated

Derived type family instances:
  type Rep StructBody = D1
                          ('MetaData "StructBody" "Ubc.Parse.Syntax.Struct" "main" 'False)
                          (C1
                             ('MetaCons "StructBody" 'PrefixI 'True)
                             (S1
                                ('MetaSel
                                   ('Just "variables")
                                   'NoSourceUnpackedness
                                   'NoSourceStrictness
                                   'DecidedLazy)
                                (Rec0 [(VariableName, VariableType)])
                              :*: S1
                                    ('MetaSel
                                       ('Just "functions")
                                       'NoSourceUnpackedness
                                       'NoSourceStrictness
                                       'DecidedLazy)
                                    (Rec0 [Function])))

but I cannot find a Monoid instance. Do you know where I could learn about this?

Thank you for your time and attention

Edit: fixed a problem with a deriving clause, added a missing code block

 

I mean the Voyager 1 probe which is currently the human-made object the farthest away from earth. The space program people operating the mission seem to have great control options, they even "moved software from one chip to another" (link) Apart from the probably gigantic and expensive installation needed to receive and/or send messages from/to that far away from home (23 hours of delay?), are there any safety measures to prevent a potentially malicous actor from sending commands to the probe?

 

Up until now I simply used Element, it just works and it doesn't look too bad. Unfortunately, I now have two Matrix accounts, my personal account and the account my university automatically created on their own matrix instance.
I need to communicate using both my accounts now, but Element couldn't handle two accounts at the same time, so I went on to install a second client, Fractal, which also supports multiple accounts. However, I am somewhat unhappy with Fractal because I cannot select text in messages.

Please share your experiences and recommendations with or on matrix clients.

 
 
 
view more: next β€Ί