[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

/fpt/ - Functional Programming Thread

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 316
Thread images: 24

File: 1481028595322.png (292KB, 480x386px) Image search: [Google]
1481028595322.png
292KB, 480x386px
Next-level programming thread.
Try it, you'll like it!

Last one: >>58076404

Resources:
>Elixir
http://chimera.labs.oreilly.com/books/1234000001642/index.html
>Elm
https://guide.elm-lang.org/
>Erlang
http://learnyousomeerlang.com/content
>F#
http://fsharp.org/learn
>Haskell
https://en.wikibooks.org/wiki/Haskell
>Lisps
>>Clojure
http://www.braveclojure.com/foreword/
>>Scheme
SICP

Feel free to add more.
>>
>>58105321
Does anybody ever actually ask Haskell questions in these threads or is it pure shitposting and memes?
>>
the fuck is this shit
we already have a >>>/g/dpt/
>>
>Enter thread
>See Elixir
>See Elm
>See Erlang
>Leave thread

Bye.
>>
>>58105337
Pure and immutable shitposting and memes.
>>
File: tired.jpg (32KB, 800x450px) Image search: [Google]
tired.jpg
32KB, 800x450px
>>58105337
Last thread we had:
>2 posts with blocks of Clojure code
>1 post with psuedocode

And that was it.
>>
also, next time you create a general, make sure you put general in the subject so the filters can work
https://boards.4chan.org/g/catalog#s=dpt|wdg|sqt|general
>>
>>58105439
I guess complaining won't help so: /fpt/, what's your favorite trick or tool in your language of choice?
>>
>>58105489
/dpt/ doesn't have General in subject.
>>
>>58105523
because I already know that there's a /dpt/
>implying i want to scour the entire catalog everytime
sage
>>
>>58105517
>favorite trick
using the codensity monad to improve any free monad construction by right-associating all binds via use of the yoneda isomorphism
>>
>>58105372
Kill yourself you worthless triple bigger

What fucking difference does it make to you that this thread exists
>>
>>58105372
>>58105544

Who is this newfag trying to tell people what they are allowed to post?

Kill yourself underage faggot


>>58105321

Has anybody experience with Scala? Is it harder or easier than Haskell?
>>
Scala is harder to learn functional principles in because it is also fully oop. It also has pretty much every language feature ever. People don't actually know that Scala is technically a fully fledged dynamic Lang. You just have to add an import (it's heavily frowned upon to do this mind). The plus side is that it is more pragmatic and there are more jobs.

Haskell is more sound and will teach you fp easier (as you can't back out) but can be really unforgiving if you don't understand certain concepts.

They are both fine Langs.
>>
>>58105337
Feel free to
>>
>>58105746
I want to answer Haskell questions, not ask them - I know a lot about Haskell already, and can't think of any open questions I'd have
>>
>>58105517
I'm new to functional field, so overall concepts of FP do amuse me.
>>
>>58105321
When will this meme die?
>>
>>58105732
>one will land a good job, but you will be called pajeet forever
>the other will not land you a job, and you will be called hipster faggot forever
>>
What's the best basic math book?
>>
>>58106687
>>
>>58106710
Too advanced, i can't even add yet
>>
Scala Circe.

JSON serialisation and deserialisation in a completely type safe way. Code generated at compile time , no reflection or macros.

All you need to do is an import.
>>
>>58105372
Get out of here, you reddit tourist.
>>
>>58106725
Haskell has Generics for this, and Aeson does JSON

{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic)
import Data.Aeson (ToJSON, FromJSON)

data MyDataType ... ... ...
deriving (Generic)

instance ToJSON MyDataType
instance FromJSON MyDataType
-- no implementation needed
>>
>>58107194
This is how it's implemented in Scala as far as I know.
>>
File: oo.png (22KB, 620x200px) Image search: [Google]
oo.png
22KB, 620x200px
Haskell has classes.
What went wrong?
>>
I'm currently learning Haskell as my first programming language (not strictly true, I programmed when I was younger and dabbled in things ranging from C++ to our old favorite, Visual basic 2006, but it has been long enough that I only know programming concepts and not languages anymore) and am enjoying it so far, but I'm wondering if it is the best functional programming language to learn, or if there is one that has significant advantages over it for general use and better lasting impact on me in terms of teaching me programming skills that will translate into other languages.

For reference it won't have much application with my job, and will mostly be a resume booster and fun hobby.
>>
>>58107628
What do you mean?
>>
File: 304TFsn.png (162KB, 453x435px) Image search: [Google]
304TFsn.png
162KB, 453x435px
just started learning haskell today
how to fix this?
import System.Random

comp n rand =
if n < rand
then print "too small"
else if n > rand
then print "too big"
else return ()

main = do
xxx <- randomRIO(1, 100) :: IO Int
comp (readLn :: IO Int) xxx


main.hs:12:27: error:
• Couldn't match expected type ‘IO Int’ with actual type ‘Int’
• In the second argument of ‘comp’, namely ‘xxx’
In a stmt of a 'do' block: comp (readLn :: IO Int) xxx
In the expression:
do { xxx <- randomRIO (1, 100) :: IO Int;
comp (readLn :: IO Int) xxx }
>>
>>58107668
He means type classes without actually knowing they are completely different from oop classes.
>>
>>58107825
comp takes a regular integer (or anything that can be ordered)

readLn isn't an int, it's an IO int
So you need to "extract" the int in do-notation

n <- readLn
>>
>le useless academic meme thread

Next we'll have an esoteric programming thread.

Sage, hide and report.
>>
>>58107907
This isn't even the worse bait I've seen today
>>
>>58107919
You mean this thread?
>>
>>58107929
No, I mean the part where you said you had a job, a life and a girlfriend.
>>
My favourite functional programming language is JavaScript.
>>
>>58107934
If you call that college undergrad research grant a "job", fine.
>>
>>58107907
>>58107940
Ha ha very funny. You can go now.
>>
>>58107948
So can you. This board is about technology, not fringe academic theories that have no practical purposes. Technology implies practicality.
>>
>>58107964
No, honestly, you aren't funny.
You're just spamming and shitposting.
Fuck off already.
>>
>>58107634
Seconding this. I want to make sure Haskell is the one worth getting into, and if not, what is?
>>
>>58107825
comp n rand =
if n < rand
then print "too small"
else if n > rand
then print "too big"
else return ()


guard syntax would be much better for this kind of multi-way-if construction

comp n rand
| n < rand = putStrLn "too small"
| n > rand = putStrLn "too big"
| otherwise = return ()


Or another way you could do this is via pattern matching, e.g.

main = do
target <- randomRIO (1, 100)
input <- readLn

case compare input target of
LT -> putStrLn "too small"
GT -> putStrLn "too big"
EQ -> return ()
>>
>>58107971
Pretty sure you meant to quote >>58105321 instead.
>>
>functional programming

That's a funny way to say "esoteric programming".
>>
Any good Common Lisp books?
Currently reading Practical Common Lisp (http://www.gigamonkeys.com/book/), but I wonder if there are any better alternatives...
>>
>>58108047
>>58108033
>>58108032
>>58108030
>>58107976
>>58107964
>>58107907
>>58107929
>>58107947
>>58107940
Please take a screenshot of this post, I want to see how many (You)s there are
>>
File: screenshot.png (70KB, 1089x341px) Image search: [Google]
screenshot.png
70KB, 1089x341px
>>58108063
No, leave /g/.

>>58108069
Sure. Here you go.
>>
>>58108063
Stop.
>>
>>58108106
>>58108109
>>58108110
>>58108117
What psyop tactic did I accidentally stumble into here?

I mean the goal is pretty clear, but I wonder what the motivation is? Who would possibly gain anything from censoring knowledge? Presumably, people who want to prevent it from spreading.

The most astonishing thing is that it's not just one guy, it seems to be some form of collective effort at the very least. Has Oracle started hiring people to ensure Java job security by preventing progress? Seems a bit weird to be doing that on 4chan, of all places.

Another possible motive would be somebody bitter and angry that he couldn't figure something out, trying to eliminate all mentions of it / belittle it to make himself feel better about it; but that wouldn't explain the high degree of organization.

Anybody else have an idea? Genuinely interested now
>>
>>58108106
>>58108109
>>58108110
>>58108117

Love you too guys!
Not OP, by the way
>>
File: 1482287377939.png (480KB, 600x849px) Image search: [Google]
1482287377939.png
480KB, 600x849px
Have you programmed in Mathematica today?
>>
File: karen haskell.png (818KB, 1280x719px) Image search: [Google]
karen haskell.png
818KB, 1280x719px
>>58108169
It's literally just someone with autism who thinks he's funny.
He was probably bullied as a child. Sad, really.
>>
>>58105321
been dicking around with clojure recently (rorfag here. yeah yeah but it pays the rent and leaves me with an extra 8 hours a day for jerking off)

anyway I got the joy of clojure since I like that guy's blog and honestly I think it's one of the only "how to $LANG" book I've liked

it goes fast and assumes you know how to google, but it has been pretty useful for coming up to speed

anyway if you can't stand most intro books but want a nice tour I recommend it
>>
File: kode.png (1MB, 1357x1281px) Image search: [Google]
kode.png
1MB, 1357x1281px
>>58107825
>>58107906
>>58107975
thanks, so I have this. Is there something I should change or this is acceptable?

import System.Random
import Control.Monad.Cont

comp n rand
| n < rand = print "too small"
| n > rand = print "too big"
| otherwise = print "yep"

main = do
xxx <- randomRIO(1, 100) :: IO Integer

forM_ [1..] $ \_ -> do
a <- readLn :: IO Integer
comp a xxx

>>
>>58108569
If you don't care about the number (or the result), you can use
replicateM_
from Control.Monad (it might be in Cont)

If you want to do it forever, you can use
forever
(also from Control.Monad)
e.g.
forever $ do
a <- readLn
comp a xxx


You could break up the functionality in comp too.
If you look at it, in every case you produce a string, and then print it. So you could just as easily do

comp n rand
| n < rand = "too small"
| n > rand = "too big"
| otherwise = "yep"

and then

print (comp a xxx)
>>
>>58108569
1. ‘print’ does not do what you think it does. The function for printing a string to stdout is putStr / putStrLn. ‘print’ is defined as
print = putStrLn . show
, which for strings means you'd end up with a source-code representation (including quotes and escaping)

2. If you're going to be printing the result in all cases, you could just do something like this:

comp n rand = print $ case compare n rand of
LT -> "too small"
GT -> "too big"
EQ -> "yep"


3. you could swap comp's arguments and use something like
forever $ readLn >>= comp
>>
>>58108671
>
forever $ readLn >>= comp xxx

fixed
>>
File: tumblr_mni3kogThg1riluboo1_500.png (208KB, 500x388px) Image search: [Google]
tumblr_mni3kogThg1riluboo1_500.png
208KB, 500x388px
>>58108283
>I'm bullied even on 4chan
>>
What would be the best way to implement finite states machine in Haskell ?

Am I an idiot if I tough of that ? :
data States      = States [Int]
data Transitions = Transitions [(Int, Char, Int)]
data InitStates = InitStates [Int]
data FinalStates = FinalStates [Int]

data Automate = Automate (States, Transitions, InitStates, FinalStates)
>>
File: wire defusal problem.png (277KB, 2780x860px) Image search: [Google]
wire defusal problem.png
277KB, 2780x860px
>>58110076
Depends how crazy you wanna go
>>
>>58110120
I'm looking for something basic/naive.

And shit this is some trve power level here
>>
>>58110272
you can represent the states as a data type and the state transitions as functions
>>
>>58110478
I just though about the transitions as functions yeah.

Shit gets messy with tuples
>>
>>58105517
F# active patterns are a super-useful construct. It's nice to be able to generate my own pattern-matching forms and have that act-on-data-then-match it form. Definitely feels like an F# "killer feature".
>>
>>58110510
active patterns are good and it would be nice to see higher order patterns in haskell
>>
File: 1473353326010.png (302KB, 1920x1080px) Image search: [Google]
1473353326010.png
302KB, 1920x1080px
roll and post your results in your favorite functional language
>>
>>58110076
Here's a simple DFA implementation I made as part of a DFA->regex thing

data DFA = DFA { alphabet :: [Char], states :: Int, start :: Int, finals :: [Int], fun :: Int -> Char -> Int }

checkD :: DFA -> String -> Bool
checkD d s = go (start d) s `elem` finals d
where go !n [] = n
go !n (x:xs) = go (fun d n x) xs


Use it like this:

goal :: DFA
goal = DFA { alphabet = "01", states = 4, start = 1, finals = [1], fun = f }
where f n '0' = case n of 1 -> 2; 2 -> 1; 3 -> 4; 4 -> 3
f n '1' = case n of 1 -> 3; 3 -> 1; 2 -> 4; 4 -> 2

test :: DFA
test = DFA { alphabet = "01", states = 2, start = 1, finals = [2], fun = f }
where f 1 _ = 2
f 2 _ = 1


Here's the full code, if you're interested: https://0x0.st/9y4.hs

It's not 100% correct, there are still some bugs in my O(n*m) regex matching algorithm. (I had an exponential version which was correct, but too slow). Can't be bothered to waste more time on it though.
>>
>>58110510
>>58110544
Can you provide a quick example in F#? I want to see how close I can get in Haskell
>>
>>58110979
in Haskell you'd use ViewPatterns or PatternSynonyms
>>
Tell me why i should switch over from c++
>>
>>58111023
C++ is one of the worst languages ever designed
>>
>>58111023
>>58111042
Oh and it's gradually trying to adopt FP features but it's far, FAR too late
>>
>>58111012
Yeah but I mean, what do active patterns provide on top of ViewPatterns + PatternSynonyms?
>>
>>58111023
c++ is a huge mess,
it has a ton of oddities and quirks, and hacks to get around them.

and it will only get worse as it tries to add new features while keeping backwards compatibility (aka mistakes)
>>
>>58111162
ViewPatterns + PatternSynonyms are pretty much equal to active patterns

But there are things Haskell is missing, e.g.
or-patterns:

case x of
0 || 1 -> "got 0 or 1"
-- trivial example
a 'c' x || b 0 x False -> show x
-- bind the same variables, so we can combine them

and-patterns

case x of
(0, y) & (_, (_, z, _))
(in this case you can use an as pattern)

as patterns are generally a subset of and-patterns

lifting a -> Maybe b
case list of
safeHead x -> ...
(use viewpatterns)

case list of
safeHead -> Just x

patterns are kind of second class citizens and guards are another example
>>
>>58111056
If C++ drops C heritage, it would be better.
>>
>>58111288
If you want to have patterns as a first-class-citizen in Haskell, you should look into Prisms (from the lens library). There's sadly no built-in syntax for them, but you can define whatever prism you want and then wrap a pattern synonym around it.

Prisms can trivially do or/and/view patterns, as well as stuff like prism composition.
>>
>>58111338
if languages don't dress up as C '''CS majors''' can't understand them
>>
>>58111338
C++ is never going to be good
>>
What's a less retarded way of doing this? I'm just starting out.
operation :: String -> Float -> Float -> Float
operation op x y -- op, x and y are user input
| op == "+" = doAdd x y
| op == "-" = doSub x y
| op == "/" = doDiv x y
| op == "*" = doMul x y
| otherwise = 0
>>
>>58111234
for example, the problem im having right now is its "uniform" initialization syntax being not very uniform at all.
so i have to figure out all sorts of exception cases to get it to work properly.

>>58111338
its C stuff is mostly fine,
the biggest problem it gets from it is headers. hopefully we get to use modules soon.
>>
>>58111413
Pattern matching

operation :: String -> Float -> Float -> Float
operation "+" = doAdd
operation "-" = doSub
operation "*" = doMul
operation _ = 0
>>
>>58111413
>>58111629
Or perhaps even something like this (for less repetition)

operation = \case
"+" -> doAdd
"-" -> doSub
"*" -> doMul
_ -> 0
>>
>>58111363
>as C
You wanted to say "as Algol".
>>
I am a program engineering student and we don't see functional programming, but from what i read functional programming is all about having no state
>>
File: 1414755619067.jpg (49KB, 600x900px) Image search: [Google]
1414755619067.jpg
49KB, 600x900px
>>58108063
Land of Lisp was really good. By the time you get to the end of the book, you have done something actually kind of crazy, and you don't realize what it is until you get 90% of the way there. (Which is why I am not specifying what "it" is, because it's a really cool realization.)

It's also a fun book.

I highly recommend it.
>>
File: 1412514503015.jpg (28KB, 500x500px) Image search: [Google]
1412514503015.jpg
28KB, 500x500px
>>58110973
Jesus, thank you anon
>>
>>58110120
Puzzle-oriented programming
>>
>>58112617
Thanks anon, I'll check it out
>>
Should I get better at imperative programming in general before learning something like Haskell? The only thing I've done so far is C.
>>
>>58113699
You should do whatever interests you and you enjoy doing.
>>
>>58110625
roll
>>
>>58114287
Hmm, I'm undecided as to how much effort I want to put into this

From easy to difficult:
>trivially embedding data into the low bits of a lossless file format
>making the embedded data match a real-world noise distribution more accurately
>embedding data into lossy images (e.g. JPEG) by perturbing the highest-frequency DCT bits, then recompressing the result losslessly

if singles first
if dubs second
if trips third
>>
>>58105523
I think he searches for the dpt, wdg, sqt, and finally for any threads that have general in the title, to see if there are any new generals.
>>
>>58114450
{-# LANGUAGE Rank2Types, FlexibleContexts, ConstraintKinds #-}

import Codec.Picture
import Control.Lens
import Data.Bits
import Data.Bits.Lens
import Data.ByteString (ByteString, pack, unpack)

type RealPixel a = (Pixel a, Bits a, Num a)

stegBits :: RealPixel a => Int -> IndexedTraversal' Int (Image a) Bool
stegBits n = imagePixels . taking n bits

embed :: RealPixel a => Int -> ByteString -> Image a -> Image a
embed n bs = partsOf (stegBits n) .~ (unpack bs >>= toListOf bits)


The reverse function (‘extract :: Int -> Image a -> ByteString’) is left as an exercise to the reader, but it's essentially the dual of ‘embed’, i.e. the same thing in reverse.

As usual, solving anything in Haskell ends you up with more lines of imports and language pragmas than actual code.
>>
Going to try Clojure, my first Lisp after a couple weeks of Haskell.
Desktop's keyboard broke and my VM that I was playing with Haskell in is now... Well unusable in the meantime.
>>
File: me.jpg (42KB, 512x512px) Image search: [Google]
me.jpg
42KB, 512x512px
>>58105321
Which functional languages have the most libraries for machine learning or are most suitable for machine learning?
>>
>>58111413
functions = [
("+", (+)),
("-", (-)),
("*", (*)),
("/", div) ]

... lookup ...

>>
>>58115907
Probably Clojure, but that's mostly because of DeepLearning4J, which is a very good Java ML library: https://deeplearning4j.org/
>>
>>58116950
I should note, that even though it is a Java library, it pays a reasonable amount of attention to its Clojure use.
>>
>>58105758
Post best guides to Haskell not the shitty LearnYouhaskell for kids shit.
>>
>>58105321
What's the functional programming language with the coolest syntax? Hard mode: no mainstream languages like Haskell allowed
>>
>>58117810
Idris
>>
>>58105321
AYO HOL UP

>>Scheme
The Little Schemer
>>
>>58117810
I think we are used to seeing it here now, but I still think the amount of syntax in Lisps are astonishing.
>>
>>58118286
That looks basically the same as Haskell. I want something different and cool and beautiful and mathsy.
>>
how would you make map in C?
>>
>>58118651
haskell
>>
>>58118651
APL
>>
>>58118772
>APL
>Beautiful
>>
>>58107634
>>58107973

I started with Scala to start off but it's too easy to end up writing was basically amounts to Java. F# forces you to write functional code and you'll fall in love with the pipeline operator once you get it.
>>
>>58118917
write Haskell instead
>>
>>58118917
What's the pipeline operator?
>>
>>58118993
f |> x = f x


it's just reverse function application
>>
>>58119012
You botched the code.
>>
>>58119075
whoops

x |> f = f x
>>
>>58118723
#define defmap(T)
void map_##T(T (*f)(T), T *in, T *out, size_t n) { \
for (int i = 0; i < n; i++) out[i] = f(in[i]); \
}
#define map(T) map_##T
>>
>>58119170
add \ after first line
woops
>>
>>58119012
>>58119132
As someone who doesn't know Haskell or F# I have no idea the implications of this.

How would one use that?
>>
>>58119223
https://bartoszmilewski.com/2011/01/05/using-f-sequences-and-pipelines/
>>
>>58118723
           main(l
,a,n,d)char**a;{
for(d=atoi(a[1])/10*80-
atoi(a[2])/5-596;n="@NKA\
CLCCGZAAQBEAADAFaISADJABBA^\
SNLGAQABDAXIMBAACTBATAHDBAN\
ZcEMMCCCCAAhEIJFAEAAABAfHJE\
TBdFLDAANEfDNBPHdBcBBBEA_AL\
H E L L O, W O R L D! "
[l++-3];)for(;n-->64;)
putchar(!d+++33^
l&1);}
>>
>>58119223
1 |> (+1) |> (*2) |> (2^)
>>
>>58110625
Hi. I mean this with all sincerity. What's the best way to practice these things? I'm not a programmer at all, and I won't be able to learn academically for 1 year until I start school. I want to practice 100% sincerely making this my hobby full time. Is this supposed to be a sequential list of things to practice? Or what is the best way to start to learn? I know that I at least want to learn JS and Python/R well. Anything you might have to suggest? Reddit was 0 help at all and I just feel lost because I live in a dirt shit poor anti-intellectual area of America that's been de-industrialized and no one knows any tech at all. Thanks.
>>
>>58119326
No, the point is that the last 2 numbers of your post are 26 so you should make a radix converter
>>
>>58119326
You can read books and do tutorials on a whatever language interests you the most until you think you can almost imagine how write one of the things on the image.

Then you roll and do whatever it is you got. (The last two numbers of your post, so you would have challenge 26 if you rolled here)
>>
>>58119252
>>58119283
Oh, so it's like threading! (Not the multithreading type)

Thanks for the link anon.
>>
>>58119343
Thank you so much. Is instruction via textbook the way to go to become proficient? Or is the "hack" method of learning as you do the way to go?
>>
is there no programming language that looks like mathematical notation?
>>
>>58119391
Book
>>
>>58119274
>mom, look at me, mom, I can put bullshit in for loops, mom!
>>
File: 1450379066800.png (24KB, 189x189px) Image search: [Google]
1450379066800.png
24KB, 189x189px
>>58119391
That depends on whichever way you learn best.
Either way, you'll need to read stuff though.

A mix of the above generally works pretty well for most people it seems. I suggested tutorials and books because they can give fundamentals in a good order, but they aren't actually required.

For example, if you wanted to learn Clojure, I would recommend working through this a little http://www.braveclojure.com/
Then when you think you can, to solve problems on https://www.4clojure.com/ or to work on little side projects... Just little dumb things you think you might want to try.

The neat part about this is that when you get stuck, you can just go back to reading Brave Clojure, which gives you time to think of ways to get around whatever blocked you, and if you get stuck long enough, the book might just tell you how to do that thing or show you why your thinking is wrong!

The thing is, the more stuff you try, the more you learn--and functional languages are fantastic for trying things out.
>>
>>58119405
No, they're mostly text based
>>
>>58119405
>is there no programming language that looks like mathematical notation?
APL
https://en.wikipedia.org/wiki/APL_(programming_language)
>>
>>58110625
poлл
>>
How can you change Hotkeys in Vim? My german Keyboard cant Do some of them, because of reasons
>>
>>58120410
If you can type it at least once, you can have as many ":nmap <newkey> <oldkey>" lines to remap those things in your vimrc.

I don't know if there is a better way to do it, I'm actually an Emacs guy.
>>
>>58120435
Oh, I should note that <newkey> and <oldkey> work with key sequences too. You just put one key after the other with no spaces.
>>
>>58118917
>and you'll fall in love with the pipeline operator once you get it.
x |> f = f x
infixr 0 |>


wanna fall in love with haskell now?

although the usual name for this in Haskell is &, so you'd just write
someComputation & doSomething & doSomeOtherThing
(where in F# you would use |>)
>>
I'm learning Clojure and you can't stop me
>>
>>58120562
sorry, should be infixl not infixr
>>
>>58118917
>>58120562
Functional pipelines are the best. Here is what they look like in Clojure.
(->> (range)
(filter even?)
(take 10)
(reduce +)
(+ 1))


This takes an infinite list of numbers, filters out the odd ones, takes the first 10 of those adds them all together, and adds 1.

There are quite a few threading macros in Clojure actually: http://www.spacjer.com/blog/2015/11/09/lesser-known-clojure-variants-of-threading-macro/

>>58120565
Good choice.
>>
>>58120671
Here's how they look in Haskell

(+1) . sum . take 10 . filter even $ [1..]


or if you want to use multiple lines like that
    (+1)
. sum
. take 10
. filter even
$ [1..]


Although I find this style of programming to be really ugly, personally. Also I would probably write this code like that:

sum [2,4..20] + 1
>>
>>58120722
Ooh. That's pretty slick!

>or if you want to use multiple lines like that
I used multiple lines because I had a number of forms.
I also think it looks nicer on one line if you don't need to add anything to the invocation.
>>
>>58120778
If my thing is longer than 80 cols if put on a single line, I break it up into multiple sub-definitions
>>
{-# LANGUAGE GADTs, TypeOperators #-}
data Pipeline a b where
(:>) :: (a -> b) -> Pipeline b c -> Pipeline a c
Fin :: Pipeline a a
infixr 0 :>

..
process = enumFrom :> filter even :> take 10 :> sum :> succ :> Fin

..
run :: Pipeline a b -> (a -> b)
run Fin = id
run (f :> g) = run g . f

..
run process 1
>>
>>58120800
another alternative

{-# LANGUAGE RebindableSyntax #-}
import Prelude hiding ((>>))

(>>) = flip (.)

process = do
enumFrom
filter even
take 10
sum
succ

..
process 1
>>
>>58120800
Why so complicated?

(>>>) = flip (.)

process = enumFrom >>> filter even >>> take 10 >>> sum >>> succ
>>
>>58120827
or, of course, just
process = succ . sum . take 10 . filter even . enumFrom
>>
first time doing this so I have no idea. I want to brun a windows 10 iso onto a usb and I'm using manjaro linux.
Used to using a gui (windisk32) so no idea how to do it on linux.
how do I do it?
>>
>>58120827
(>>>) is verbose and i was showing alternatives
>>58120834
is backwards
>>
>>58120786
Yeah, I try really hard to keep things less than 80 columns, but I don't think I have ever run into a threading case where having things on one line broke that.

I guess what I mean is that for simple things, I:
(-> thing a whole bunch of calls)

Because it is cleaner.

I also have "->" instead of "->>" here because they only take one argument anyway, and "->" threads successive calls as the first argument.
However, these don't need to be bare symbols, you can add parens to the things you want to add additional arguments to.

For more complicated things I split it up into separate lines because it is cleaner IMO:
(->> thing
(filter predicate)
(map somefunc)
(partial + 3)
(take something))


This sort of style does not translate well to Haskell it seems.

>>58120834
Functional pipelines are the best.
I'm kind of spoiled because it pains me when I can't use things like this when working with collections.
>>
>>58120882
>This sort of style does not translate well to Haskell it seems.
Blind or stupid? There are like 10 examples in this thread of how to translate that exact style of programming to Haskell
>>
>>58120898
I was talking about appearance. It's ugly to split lines when you add additional arguments to a pipeline function.
But thanks anyway.
>>
>>58120898
That was in reference to >>58120722
>or if you want to use multiple lines like that
>Although I find this style of programming to be really ugly, personally.
>>
>>58120935
To be fair, I included a formatting error in my example (meant to align the $ with the .)

It has less syntax than the (->>) garbage from Clojure, so it's still prettier than that I suppose. I was just pointing out that I hate the pipeline style of programming.
>>
>>58120958
Fair enough. I like it because it keeps code that would give you deeply nested s-expressions clean.

Clojure has very little syntax, which is both a good thing and a bad thing.
It's a good thing for practical reasons, such as macros.
But it's also a bad thing because it means there are few ways to manage how your code looks outside of code transformations.
>>
>>58120995
>Clojure has very little syntax, which is both a good thing and a bad thing.
I measure syntax by the number of special characters - and parens count double. Having () everywhere is a lot of syntax noise, to me.
>>
>>58121028
Clojure have various parens to remove Lisp words, IIRC.
>>
>>58121028
Well, it's almost all parenthesis, and that's the point.

Of course, if you don't like it you don't like it.
>>
>>58121053
Kinda. But special syntax for things is mostly limited to anonymous functions and data types.

So it does have slightly more syntax than most Lisps, but not by a lot.
>>
>>58120882
Haskell

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, TypeFamilies #-}

newtype Fin a = Fin { run :: a }

class Pipe a b where
(->>) :: a -> b

instance a ~ b => Pipe a (Fin b) where
(->>) = Fin

instance (Pipe b c, x ~ (a -> b)) => Pipe a (x -> c) where
(->>) a f = (->>) (f a)

process :: Int
process = run ((->>) (enumFrom 0)
(filter even)
(take 10)
(sum)
(succ))


:^)
>>
>>58121110
Nice :^)
>>
>>58121110
Line 5 should have been
class Pipe a b | b -> a where
but otherwise fine
>>
>>58121110
I see what you did there
>>
>>58108063
Common Lisp Recipes by Weitz
>>
>>58121110
>>58121153
>>58121114
Got rid of the superfluous ‘run’ as well

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances,
UndecidableInstances, TypeFamilies, DataKinds, PolyKinds,
ScopedTypeVariables #-}

data Proxy t = Proxy

type family IsFunction (a :: *) :: Bool where
IsFunction (a -> b) = True
IsFunction x = False

class Pipe (f :: Bool) a b where
pipe :: proxy f -> a -> b

instance a ~ b => Pipe False a b where
pipe _ = id

instance (f ~ IsFunction c, Pipe f b c, t ~ ((a -> b) -> c)) => Pipe True a t where
pipe _ a f = pipe (Proxy :: Proxy f) (f a)

(->>) :: forall f a b. (f ~ IsFunction b, Pipe f a b) => a -> b
(->>) = pipe (Proxy :: Proxy f)

process :: Int
process = ((->>) (enumFrom 0)
(filter even)
(take 10)
(sum)
(succ))


λ :r
[1 of 1] Compiling Main ( pipe.hs, interpreted )
Ok, modules loaded: Main.
λ process
91
>>
>>58121266
> a ~ b => Pipe False a b
How is this different from
Pipe False a a

?
>>
>>58121273
‘Foo a a’ only matches when you already know that the two variables are the same

‘a ~ b => Foo a b’ *always* matches, and then forces a and be to be the same

The trick is to realize that instance selection is done by *only* looking at the instance head (e.g. Foo a a and Foo a b), and then the contexts are pulled in based on the selected instance.
>>
>>58110625
rolling
>>
>>58110625
another roll for Haskell
>>
>>58121439
What's a “scientific calculator”?

Anway, I already implemented a proof-of-concept RPN calculator. Adding features is just fluff: https://0x0.st/u5.hs
>>
Should I make the switch to functional programming if I do everything in C and already love it?
>>
Any examples of a software that is actually written in a functional language?
>>
>>58121450
Has sin, tan, pow, log, root, etc.
>>
>>58121630
ghc
>>
File: t.jpg (51KB, 800x500px) Image search: [Google]
t.jpg
51KB, 800x500px
>>58121646

Back to China with you!
>>
>>58121646
fine

--- clac2.hs.orig    2016-12-22 15:30:06.664069467 +0100
+++ clac2.hs 2016-12-22 15:31:12.953349537 +0100
@@ -54,6 +54,11 @@
, "!" ~> op (product . enumFromTo 1)
, "pi" ~> op (pi :: Double)
, "sum" ~> opn sum
+ , "sin" ~> op sin
+ , "cos" ~> op cos
+ , "tan" ~> op tan
+ , "log" ~> op log
+ , "exp" ~> op exp
]

class Op t where


happy now?
>>
>>58121646
>>58121860
Okay, that was pretty funny.
>>
>>58121880
M+ / M-
>>
Don't know which language should I try as my first functional, I tried Scheme once and I liked it but SICP was too hard so I quit. Any other resource?
>>
>>58121911
Haskell, see OP
>>
>>58121898
fine, have this. it's equivalent in power

--- clac2.hs.orig    2016-12-22 15:33:58.074601029 +0100
+++ clac2.hs 2016-12-22 15:37:31.411425004 +0100
@@ -59,6 +59,7 @@
, "tan" ~> op tan
, "log" ~> op log
, "exp" ~> op exp
+ , "dup" ~> opDup
]

class Op t where
@@ -83,6 +84,10 @@
opn :: ([Double] -> Double) -> String -> Operation
opn f n (reverse -> xs) = Right [(f $ map fst xs, Node n $ map snd xs)]

+opDup :: String -> Operation
+opDup n [] = Left $ Node n [Node "?" []]
+opDup n (x:xs) = Right $ x:x:xs
+
usage :: [String]
usage =
[ "Example:"


Pretty sure it's now turing complete

p.s. it has pretty errors

λ ./clac2.hs "1 2 + *"
Stack error:
(*)
|
----
/ \
(+) ?
|
--
/ \
1 2

λ ./clac2.hs "1 2 + foo * bar"
Parse error:
1 2 + foo * bar
^^^ ^^^
>>
>>58121944
>Pretty sure it's now turing complete
Actually it was trivially turing complete before, because of multiplication and addition
>>
>>58119391
The best way to learn is to start off with the "hack" method then read a book, at least in my opinion. So I would first read a short tutorial on a language, then implement something basic, so I'd have an idea about the big picture, and I could see the motive behind the things in the book. Otherwise I'd be thirty pages in still reading about the different data structures and I still wouldn't get how all this could ever be useful. This is why the entire first chapter in the famous C book K & R is a short tutorial.
>>
Why would being turing complete say anything about the quality of the language? I would love to see more purely declarative languages.
>>
>>58122112
If the language *isn't* turing complete, that says a great deal about the sophistication of that language.

For example Agda, Idris and Coq are some of the most advanced languages around, and they're all not turing complete. Also, turing completeness is a bad sign in other areas like protocol design and file formats in general.

tl;dr turing completeness is a meme
>>
File: d319f9f45d98969954417f3422d39e60.png (811KB, 1000x1333px) Image search: [Google]
d319f9f45d98969954417f3422d39e60.png
811KB, 1000x1333px
>>58122140
>Agda
 data _≤_ : ℕ → ℕ → Set where
z≤n : {n : ℕ} → zero ≤ n
s≤s : {n m : ℕ} → n ≤ m → suc n ≤ suc m


That's exactly my dream language, thanks anon!
>>
>>58121524
You don't have to make the switch, you can use two different types of programming for different projects. Functional programming is pretty fun imo, it makes you think about problems in a different way, and you'd definitely get more out of it than out of learning another C-like language.
>>
>>58122140

What the fuck am I reading??

An imperative language is Turing complete if it has conditional branching (i.e. if-statement) and the ability to change an arbitrary amount of memory (set variables).

Even "Conway's Game of Life" is a turing machine.
>>
>>58122264
>An imperative language is Turing complete if it has conditional branching (i.e. if-statement) and the ability to change an arbitrary amount of memory (set variables).
You forgot the most important part. To be turing complete, you need at the *very least* some sort of looping construct.

Agda, Idris and Coq don't allow infinite loops, therefore they are not turing complete.
>>
>>58122323
Is English turing complete?

If you want to know it read my post!
>>
>>58122212
Agda is pretty cool, you might like Coq too
>>
If you don't post the Sieve of Erastothenes in Haskell in the next five seconds
                                                                                                                                                                       .                                                                                                          .                                         nothing will happen. NOTHING
>>
>>58123036
Wrong
>>
>>58123036
what if i do?
>>
File: qq.png (12KB, 1633x225px) Image search: [Google]
qq.png
12KB, 1633x225px
>>58123036
Why is your post formatted all faggoty?
>>
File: 1480650699656.jpg (1MB, 3451x2635px) Image search: [Google]
1480650699656.jpg
1MB, 3451x2635px
>>58123064
Hi newfag

>>58123050
May you recursively burn in hell

>>58123044
                                 .                                                                                                                     ........................                                                                                                                                                                 ...................................................                                                                                         ..............................................................................................................................................                                                                                                                                .........................................................................................................................................................................................................................................................................................................                                                                                                                                                                for you
>>
>>58123084
Are you trying to use code tags as an impromptu spoiler?

If so, that's pretty faggoty.
>>
>>58123107
It's a hack
>>
>>58123107
:3
no bully pls
>>
>>58123084
according to this chart I'm sort of in between advanced sysadmin and senior sysadmin

I do about 70% of the stuff on the right regularly
>>
>>58123133
According to this chart sysadmin are penguins thus shouldn't considered as humans.
>>
>>58110625
rerolling, dont want to make a static website generator
>>
>>58123471
long TriangleNumberCalculator(int input)
{
return Range(0, input + 1).Aggregate((x, y) => x + y);
}
>>
>>58123524
sum . enumFromTo 0 . succ
>>
>>58123524
>>58123567
tri x = sum [1..x+1]
>>
>>58123747
pointy
>>
>>58110625
Rolling for agda
>>
>>58123955
nobody gives a shit
>>
>>58117789
http://haskellbook.com/
>>
>>58119448
Hi. Thank you. Do you have any specific recommendations for JS/Python in particular? I really appreciate anything that you might have. I think that I'll start looking at book reviews.
>>
Name            : ghc
Installed Size : 1146.92 MiB

why
>>
>>58127227
let me guess, braindead debian packaging? it's 330 MB for me (gentoo)
>>
>>58125640
For JavaScript, Secrets of the JavaScript Ninja is pretty great. It was written by the guy who made jQuery and is absolutely filled with incredibly useful information.

No clue for Python. I heard that Automate the Boring Stuff with Python was good, though I haven't actually read it myself.
>>
>>58127798
Oh, and for challenges, CodeWars is pretty good: https://www.codewars.com/
The best answers to most of them in JavaScript tend to be pretty functional.
>>
i wrote some nasty haskell today

-- prints a random fortune from a given file

import System.IO
import System.Random
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as L
import qualified Text.PrettyPrint as P

fortSplit = T.splitOn $ T.pack("\n%\n")
randInt x g = fst $ randomR (0, x-2) g

main = do
file <- L.readFile "fortune"
let fortunes = fortSplit file
g <- getStdGen
let randex = randInt (length fortunes) g
putStrLn $ P.render $ P.text $ T.unpack $ fortunes !! randex


also
import System.IO
main = do
input <- getContents
print $ render $ getSums input

getSums xs = map sum $ (map (map read) $ map words $ tail $ lines xs :: [[Int]])

render x = unwords $ map show x
>>
>>58120958
>I was just pointing out that I hate the pipeline style of programming.
Oh, I read that as if you didn't like the multi-line format of pipelines, and not the style in general.

Is it not idiomatic in Haskell?
>>
>>58128457
jesus christ these are disgusting
>>
>>58128550
>Is it not idiomatic in Haskell?
Depends on who you ask? I don't like it because it's (ironically) very un-functional.

‘foo = doThis . doThat . doSomethingElse’ is a very imperative style of programming. A chain like that means I'm not semantically abstracting my program into a high-level declarative description but rather a series of low-level instructions to the compuer as to what to do

Especially shit like “list these numbers, then take whatever, sum them all, then add 1” just reads like an imperative program dressed up with a different syntax.
>>
Is Scheme any good outside of SICP?
If I were learning some Lisp, what would be my best choice?
>>
Just began on Clojure for the Brave and True yesterday, and I'm on Chapter 3 and having problems.

More questions than problems, really. In the text of the book, it says that this

(defn better-symmetrize-body-parts
"Expects a seq of maps that have a :name and :size"
[asym-body-parts]
(reduce (fn [final-body-parts part]
(into final-body-parts (set [part (matching-part part)])))
[]
asym-body-parts))


works, and I tried it, it does. But when I tried to make the anonymnous function inside into its own function, it doesn't work.

Is it my approach?
Here's my attempt.

(defn better-symmetrize
[body-parts]
(reduce helper [] body-parts)
)

(defn helper
[final-body-parts part]
(into final-body-parts
(set [part (matching-part part)]))
)

(defn symmetrize-one-part
[final-body-parts part]
(into final-body-parts
(set [part (matching-part part)]))
)

>>
>>58128569
I'm not sure if I agree--at least in the context of the original example's code. (Which admittedly is not really a good example, so maybe I shouldn't defend it.)

The end goal for pipelines is generally some complex data transformation that would be noise to compose for its sake.
Because threading doesn't actually use any intermediary besides the stack, it just seems like a way to localize your concerns in a way you can throw them away after you are done because they aren't really useful elsewhere.

That's probably more important in Clojure than Haskell though. But I don't know Haskell, so I have no idea how you would usually solve a problem like that. Maybe there's a better way for me to write things?
>>
>>58128804
>Because threading doesn't actually use any intermediary besides the stack
In Haskell, that's neither really true nor really a good way of thinking about it at all. (Since Haskell is nonstrict, there's no real strict flow of function execution - it's more like a flow of data dependencies)
>>
>>58128804
>Maybe there's a better way for me to write things?
In this particular example, I would strive more for an example like >>58120722 (the last code block) or >>58123747

Basically a straight-forward, syntactical or declarative definition. I also find pointful code better than pointless code (most of the time)
>>
Does RebindableSyntax include list construction syntax?
>>
>>58128832
Ah. The approach the two languages take is really different.

Clojure is largely about immutable values flowing through your program and being transformed into the things you need using functions.

>>58128914
Yeah, that example could be simplified to that block, which is why I think it's kind of a bad example. The idea behind it however, is still quite useful.
I was just wondering if there was a different approach to pipelines in general besides the obvious composition.

>>58128789
Lisps are evaluated as if they are typed directly into a REPL, so you need to define "helper" before you use it.

>>58128710
I'm biased, but I would say Clojure. I get the impression it's the most commonly used Lisp in this thread too.
>>
is concurrency possible in haskell?
>>
>>58129023
I think it works in the same way that OverloadedStrings does

As for list comprehension syntax, that's very overloadable with MonadComprehensions
>>
>>58129136
I mean does it translate e.g. [a, b, c] to (a : b : c : []), that kind of thing.

So I could have e.g.:
class FromList f where
[] :: f a
(:) :: a -> f a -> f a

and make the syntax work for all kinds of types.
>>
>>58129170
See https://downloads.haskell.org/~ghc/8.0.1/docs/html/users_guide/glasgow_exts.html#overloaded-lists
>>
Clojure master race here. Irrelevant.haskelltards can succ me.
>>
>>58129210
That's not really ideal, it doesn't seem to allow for things like this:
data Tuple :: [*] -> * where
[] :: Tuple '[]
(:) :: a -> Tuple as -> Tuple (a : as)
>>
>>58121110
Where the fuck do I learn all these Pragmas
>>
As a sequential and OOP fag, what are the differences/benefits of functional programming? Also which language should I start with?
>>
>>58129404
Abstraction that actually works.
>>
>>58129306
ghc user guide
>>
File: 1480650157846.jpg (529KB, 595x842px) Image search: [Google]
1480650157846.jpg
529KB, 595x842px
>>58129537
(You)
>>
>>58129404
Here are three reasons from least important to most important:
>You don't need to worry about state. Know those times you debug because some value isn't want you expect it to be? No more of that.
>Functional gets rid of external dependencies for code in general. Ugly things like disks, the network, or any IO really, is isolated, which means you don't need to worry about things going wrong in nearly as many places to begin with.
>You get to shitpost on 4chan dot com about it. (See >>58129234 for reference)

The cool thing is that you can do this sort of stuff in non-functional languages too to an extent. One way to make imperative OO less prone to bugs with its state and to make it a way more testable is to write functional on the small scale, and to use OO on the large scale.

If you get comfortable with that, not only will it answer a lot of questions you might have, you will also probably really like functional code in general.

The downside is that unless a language is optimized for it, most (But not all) functional techniques are slightly slower than their imperative counterparts.
>>
>>58130118
Ok, I think I'll have a look at haskell and see what happens. Tbh functional programming seems pretty interesting.
>>
File: Oshasmile.png (31KB, 224x224px) Image search: [Google]
Oshasmile.png
31KB, 224x224px
>>58130177
Good luck..!
>>
I've asked this like 50 times but is there anyway to get a scala repl synced with emacs buffer like slime repl?
>>
>>58130531
I don't Scala, but this looks promising: http://ensime.github.io//editors/emacs/
>>
>>58130559
thanks yeah i looked into that before and looks like it requires sbt projects to be setup. I just want an emacs buffer and a repl
>>
>>58130579
Oh, if that's all you need, you could likely just set it as inferior-lisp-program and M-x run-lisp.

As a bonus, you can send blocks of code to it if by writing something similar to lisp-eval-defun and putting it in your .emacs. (Maybe make it work with the active region?)
>>
>>58130655
I'll need to look into that a little more. I'm not all that familiar with lisp and emacs integration but trying to learn some lisp now. but anyway thanks for the tips
>>
>>58130579
>>58130655
Oh, looking at inf-lisp.el I see that's actually already a thing.

M-x lisp-eval-region

There is also an M-x lisp-eval-paragraph

Just bind those to C-c C-c or something in your Scala buffers and you should be good to go.
>>
>>58130679
oh ok cool. I should be able to handle that much thanks again
>>
Hey haskell is pretty neat. I haven't even gotten into the functional programming stuff yet really but I like the set notation-like stuff
>>
>>58128457
I use MonadRandom
It's got a lot of flaws but it's nicer than messing with the rand gen yourself

And it's normally better looking to do
a . b . c . d $ x
than
a $ b $ c $ d $ x

also in many cases, like render and getSums, you can eta reduce if you use . 's
>>
>>58129023
>>58129170
>>58129253
You can't do this with RebindableSyntax, it has to be one type.

Ideally it would simply use whatever [] and (:) are in scope.
I would like these to be valid data constructor names, as well as ().
Means there's less in the language and more in the library.
>>
I want to create a data type that represents a Pair of hands with a list of Bools that tell me if a finger is up or down. How should I create this type?
data Hand = LeftHand [Bool] | RightHand [Bool]
type Pair = ???
>>
>>58132895
data Hand = Hand [Bool]
data Pair = Pair Hand Hand
>>
>>58133013
But I need to show a distinction between right and left.
>>
>>58133035
You do that by pattern matching on Pairs.
>>
>>58132895
data UD = Up | Down
type Hand = [UD]
type Pair = (Hand, Hand)
>>
>>58133045
Oh i get it, so I do something like
decode :: Pair -> Integer
decode pair = case pair of
Pair l r -> ...

thanks
>>
>>58133075
Or
decode (Pair l r) = ...

to normal people.
>>
>>58133081
Thanks for the tip
>>
>>58130118
>You don't need to worry about state. Know those times you debug because some value isn't want you expect it to be? No more of that.
This is not really true; bugs like these can and do happen in functional programs just as often - although I would argue that debugging them in functional programs is much easier because behavior only depends on its input.

>Functional gets rid of external dependencies for code in general. Ugly things like disks, the network, or any IO really, is isolated, which means you don't need to worry about things going wrong in nearly as many places to begin with.
This is also completely removed from the truth. You have to worry about disks, the network, and IO just as much in functional programs. Languages like Haskell just let you build extremely powerful abstractions for dealing with them (e.g. pipes)
>>
>>58132895
>>58133013
Hard mode

type Finger = Bool
type Hand = Vector 5 Finger
type Pair = (Hand, Hand)
>>
>>58133896
What if you lose a finger?
>>
Complete noob here
I setup Leiningen to open in emacs with cider but everytime i resolve something it prints ^M at the end of the line.
Is there a way to fix this? Thanks in advantage
>>
File: 1479978891567.jpg (18KB, 400x398px) Image search: [Google]
1479978891567.jpg
18KB, 400x398px
>>58134294
Somehow reinstalling everything fixed it
>>
>>58134740
no problem, you're welcome
>>
I think im in love with racket, it has libraries, you can do stuff with it and docs are pretty good. And unlike clojure it feels faster no waiting for jvm to boot up i can compile it or use it as python for scripting or shit.
>>
>>58110625
roll
>>
>>58134904
>it has libraries, you can do stuff with it
you're easily pleased
>>
>>58134919
already done that before, reroll
>>
>>58134925
I know! Its really sad i've come to a point when language is great coz you can actually do shit in it without too much pain...

Im working on fuzzy file/directory search. Its pretty fun, i skimed some scheme book couple of months ago but because of uni i didn't touch any lisp for months and months and its going great. Love this language.
>>
File: Capture.png (19KB, 613x371px) Image search: [Google]
Capture.png
19KB, 613x371px
Fuck i thought i fixed it
>>
>>58132114
nice one cheers, i often try and replace $ with . but it seldom works
>>
Im trying to implement levensthein in racket but i got a problem, how do i early return from function? I thought cond is solution but naah it just keeps going

(define (levenshtein s t n m)
(cond [(and (equal? n 0) (equal? m 0)) 0]
[(equal? n 0) m]
[(equal? m 0) n])
;shouldnt get to this part if n, m are 0 but it does
(+ (levenshtein s t (- n 1) (- m 1)) (matc (string-ref s n) (string-ref t m))))


And i cant seem to find a way to return prematurely, help?
>>
>>58133896
Idris?
>>
Okay, so after playing around with this some more, I got this to work;
(defn symmetrize-helper
[final-body-parts part]
(into final-body-parts
(set [part (matching-part part)]))
)

(defn better-symmetrize
[body-parts]
(reduce symmetrize-helper [] body-parts)
)



But I'm trying to do the exercises that they have, and this doesn't work.
[(defn radial-match
[part letter]
{:name (clojure.string/replace
(:name part) #"^A-" (str letter "-"))
:size (:size part)}
)

(defn radial-symmetrize-helper
[final-body-parts letter part]
(into final-body-parts
(set [part (radial-match part letter)]))
)

(defn radial-symmetrize
[body-parts]
(let [final-parts []]
(reduce radial-symmetrize-helper final-parts "B" body-parts))
)

I'm not quite sure how to do this properly, but my idea for the radial-symmetrize is that I make 4 calls of
(reduce radial-symmetrize....) with B, C, D and E.
But when I try to run this, Clojure tells me that I'm passing the wrong number of arguments (4) to Reduce, whereas if I get rid of one argument, it says wrong number of arguments (2) to radial-symmetrize.

Is there some subtlety regarding parameters that I haven't learnt/realized yet?
>>
>>58133879
>This is not really true; bugs like these can and do happen in functional programs just as often
What? That's not what I said at all.

I said you didn't need to worry about *state* screwing up the behavior of your code.
State refers to values you set in your program that are not passed into your functions. In functional code, the values you work with come strictly from its arguments.

>although I would argue that debugging them in functional programs is much easier because behavior only depends on its input.
You don't need to argue because that's literally what I was talking about.

>This is also completely removed from the truth. You have to worry about disks, the network, and IO just as much in functional programs.
I also never said you didn't need to worry about this. I said you don't need to worry about it in nearly as many places because it is isolated.

>Languages like Haskell just let you build extremely powerful abstractions for dealing with them (e.g. pipes)
Abstractions like this are the isolation I was referring to.
>>
loeb x = go where go = fmap ($ go) x
>>
>>58136255
there's a more general function
>>
>>58136255
>>58136263
moeb :: (((a -> b) -> b) -> c -> a) -> c -> a
moeb f x = go where go = f ($ go) x


loeb = moeb fmap
fix = moeb id
>>
>>58136040
It looks like you are just trying to pass three arguments to radial-symmetrize-helper, is there a reason for the reduce?

You are getting that error because reduce has no variants that know four arguments... So calling it like that will make it die with an arity issue. And when you remove an argument, it is valid, but acts very much like you wouldn't expect.

The reason you get the other error is because reduce will always call its target function (Its first argument) with two arguments of its own. The reason for that is because of what reduce actually does.
(reduce + 3 [1 2 3])


This calls + with the initial value (3) and the first thing in the list (1):
(+ 3 1)

...which returns 4, so the + is called with 4 and the next value in the list:
(+ 4 2)

...which returns 6, which makes the last call:
(+ 6 3)

...which makes the final result 9.

+ was always called with 2 arguments, and this is what you are trying to do with radial-symmetrize-helper.
>>
>>58136321

The reduce is so that it calls radial-symmetrize-helper on every part in body-parts. I was thinking that I could simply adapt my previous code for this, but clearly not.
I basically need to go through the list, and, using radial-match, match all items such as "A-eye" and create "B-eye", "C-eye" etc up to "E-eye"

Could I do this by reducing the number of arguements to radial-symmetrize? Because from what I see, when I did

(reduce symmetrize-helper [] body-parts)


I called reduce, with the function symmetrize-helper and the arguments [] and body-parts being arguments to symmetrize-helper.

I'm sorry, I don't have a very good grasp of how reduce works or how functional languages work in general.
>>
>>58134218
Oh god, is my code ableist?
>>
>>58135915
No, Haskell

data Vec :: Nat -> * -> * where
VNil :: Vec 0 a
VCons :: a -> Vec n a -> Vec (n+1) a
>>
>>58136139
>I said you didn't need to worry about *state* screwing up the behavior of your code.
Yeah, but the problem is that you'll still have state internally and throughout the evolution of your program; like e.g. if I'm writing a recursive loop or something, I have state - if I'm writing a long chain of operations, I have an implicit state that flows through the program.

Especially if you're doing something like GHC or Haddock which is a long series of tree transformations that all add and parse shittons of metadata and other associated contextual information, you have to make sure it ends up there in the right places and in the right order, and so on.

Basically, as soon as you scale FP up to the size of a full-fleged program like GHC, you gain pretty much the same issues. Just my 2 cents though.
>>
>>58136139
>Abstractions like this are the isolation I was referring to.
I guess to make my point clear, it's that these abstractions are not really a feature of functional programming per se - they're simply a feature of high-abstraction languages (haskell being one of them).

You can have high-abstraction imperative languages as well. It's just that in practice, the people who like high abstraction and simple code tend to prefer functional languages, so most of the really advanced languages end up as functional instead of imperative.
>>
>>58136516
I see, you could use reduce for that, but it would complicate things quite a bit, so I'll give a hint according to the things you just told me:

>The reduce is so that it calls radial-symmetrize-helper on every part in body-parts.
This sounds like map. And it would likely called kinda like this:

(map #(+ 3 2 %) [5 7 8])


...except you are interested in a function other than +, and will probably want a different first and second argument besides 3 and 2.

>I basically need to go through the list, and, using radial-match, match all items such as "A-eye"
This sounds like filter, and it would likely be called like this

(filter #(> 6 %) [5 7 8])


...except with your own functions and arguments.

Also, if you are using CIDER for this, try hitting C-u C-c C-c on one of your functions in a Clojure buffer. This will let you debug and step through it.
>>
Is this the general where imperative kiddos come to start the path towards logic programming? Cool, really proud of you kiddos :) Hopefully one day you'll be using prolog like real men, haha!
>>
>>58136878
Nice joke. Prolog is a dead language. Everybody who does logic programming uses an EDSL in something like Haskell or Clojure

Seriously, Prolog is an absolutely terrible language. It's basically a design concept, not a real language.
>>
>>58136789
When referring to state, I was not talking about intermediary values, but rather things that you mutate in order to change the behavior of imperative code--fields, variables, and so on...

Functional has the advantage here because you don't need to worry about these mutating values becoming unexpected things, and thus, causing your code to behave unexpectedly.

The only variance in behavior comes from the values the function is called with, and nothing else.

>>58136802
Fancy abstractions might not be, but the separation of IO from the rest of your code absolutely is.

In purely functional code, the outside world simply does not exist. If you write code to interact with the outside world, you are not writing functional code.

Since having a 100% functional program would be useless, functional languages give you some way to interact with state. This is separated from the way you do other things. Because if it isn't, you are writing imperative code in a functional language.
>>
>>58137065
>Functional has the advantage here because you don't need to worry about these mutating values becoming unexpected things, and thus, causing your code to behave unexpectedly.
I think the biggest advantage is that the strict limitation of the set of input values allows you to have a tight control over what your function can and can't do.

Honestly, the type system is 99% of what makes e.g. Haskell great, everything else is just syntactical fluff.
>>
>>58137065
>Since having a 100% functional program would be useless, functional languages give you some way to interact with state. This is separated from the way you do other things.
Another way of putting it would be that functional languages move IO into an isolated component (i.e. the runtime system), which is written in C or something of that nature.

You can also have a monad-less I/O system, at the simplest something like
main :: String -> String
or
main :: Stream Input -> [Output]
, but in all cases, I/O has to be done by the runtime system in the end.
>>
>>58128457
>let randex = randInt (length fortunes) g
OBOE
>>
>>58129023
I think you might want 'OverloadedLists'. Means you can express literal Vectors, etc using list syntax.
>>
>>58137611
>Means you can express literal Vectors, etc using list syntax.
Sadly you can't do it with DT-style Vectors, because the fromListN only gives you an Int, not a Nat
>>
>>58134904
>that JVM startup delay
Fucking kills me. That alone put me off using it.
>>
>>58135177
Sounds like a DOS/UNIX newline thing to me.
>>
>>58124920
It looks like it's not finished yet.
>>
>>58137792
^M = \r = 13 = CR (carriage return)

AKA winshit newline faggotry
>>
>>58137489
hwot
>>
>>58137078
Purity is syntactic fluff?
>>
>>58118497
>>58108063
>>58112617
>>58121210
I'll be adding those to the next OP.
>>
>>58137745
I didn't realise you could get dependently-typed Vectors in Haskell. Mind posting a link?

>>58138004
Yup.
>>
>>58139252
I think all the ones on hackage are old and abuse older Haskell features that are not as nice as the new shiny GHC 7.6/7.8/8.0 stuff (which lets you use numeric literals in the type system etc)

you should make one!
>>
>>58119326
read SICP
>>
>>58105517
Zygohistomorphic prepromorphisms desu
>>
what's the most compact fizzbuzz one can write in haskell?
>>
>>58140488
https://github.com/haasn/fizzbuzz

This one's pretty dense
{-# LANGUAGE MonadComprehensions #-}
import Data.Maybe
import Data.Monoid

fizzBuzz x = fromMaybe (show x) $ ["fizz" | x `rem` 3 == 0] <> ["buzz" | x `rem` 5 == 0]
>>
>>58140573
This one's compact while also being readable

fizzbuzz n = case (n `rem` 3, n `rem` 5) of
(0, 0) -> "fizzbuzz"
(0, _) -> "fizz"
(_, 0) -> "buzz"
(_, _) -> show n

main = mapM_ (putStrLn . fizzbuzz) [0..100]
>>
>>58140573
>monoid instance on maybes
nice
>>
learning to use haskell and want to learn how to use functions how would I set up a fxn that returns the number of factors of an integer
number_of_factors:: Int->Int
number_of_factors 0 = 0;
number_of_factors n = let x = factors n
|number_of_factors = x.length


>>
>>58140653
Yeah, that instance is really neat

import Control.Applicative
import Control.Lens
import Control.Monad (guard)

import Data.Char (toUpper)
import Data.Monoid (mconcat)
import Data.Maybe (fromMaybe)

fizzBuzz :: Integer -> String
fizzBuzz x = fromMaybe (show x) $ mconcat
[ "fizz" <$ guard (x `rem` 3 == 0)
, "buzz" <$ guard (x `rem` 5 == 0)
] & _Just._head %~ toUpper

main = mapM_ (putStrLn . fizzBuzz) [1..100]
>>
New thread:

>>58141396
>>58141396
>>58141396
>>
>>58141417
This thread was so much better than the last one.
>>
>>58141468
Pardon me?
Last one - previous to this thread?
>>
>>58141511
Yes. It was a night and day difference.
>>
>>58141533
Well, I think that's because the last one wasn't considered as serious yet.
This thread is gaining popularity, so it gets competent people. And competent people is the key to good discussion.
Thread posts: 316
Thread images: 24


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.