Menu
  • HOME
  • TAGS

Standard ML / NJ: Loading in file of functions

Tag: functional-programming,sml

I'm trying to write a bunch of functions in an SML file and then load them into the interpreter. I've been googling and came across this:

http://www.smlnj.org/doc/interact.html

Which has this section:

Loading ML source text from a file

The function use: string -> unit interprets its argument as a file name relative to sml's current directory and loads the text from that file as though it had been typed in. This should normally be executed at top level, but the loaded files can also contain calls of use to recursively load other files.

So I have a test.sml file in my current directory. I run sml, all good so far. Then I try use test.sml; and I get:

stdIn:1.6-1.14 Error: unbound structure: test in path test.sml

Not sure why this isn't working. Any ideas?

Thanks, bclayman

Best How To :

As you mentioned, the function use has type string -> unit. This means it takes a string and returns unit. When you do use test.sml, you are not giving it a string. You need to do use "test.sml" (notice the quotes)

Lazy concat in Immutable.js?

javascript,functional-programming,immutable.js

A lazy breadth-first traversal can be achieved with the Iterable API for Immutable.js: var Immutable = require('immutable'), Iterable = Immutable.Iterable, Seq = Immutable.Seq; var tree = { value: 'foo', children: [ { value: 'bar', children: [ { value: 'bar1', children: [ { value: 'bar1_a'}, { value: 'bar1_b'} ] }, {...

Easier way to apply multiple arguments in Haskell

haskell,functional-programming,composition,functor,applicative

The Applicative class has the <*> operator (usually pronounced "ap", and is equivalent to Control.Monad.ap for most Monads), which combined with the <$> operator (itself just an infix alias for fmap) lets you write code like -- f :: a -> b -> c -- fa :: Applicative f =>...

What is the type of the variable in do-notation here in Haskell?

haskell,functional-programming,monads,do-notation

Well, you've stumbled upon a kind of weird monad. The monad in question is the Monad ((->) r). Now, what does that mean? Well, it's the monad of functions of the form r -> *. I.e., of functions that take the same type of input. You asked what the type...

in clojure, function argument type mismatch

clojure,functional-programming,lisp

You are misunderstanding the format of a function definition. In your function, the single argument 'colors' is untyped and can be anything. The square brackets are used to denote the beginning and end of the arguments list (i.e. the symbols for the arguments are wrapped in a vector to distinguish...

SML - Find element in a list and substitute it

string,list,find,sml,substitute

You're making this way too complicated. This first function looks up a string in the first list: fun lookup ((a,b)::xs) v = if v = b then a else lookup xs v | lookup nil v = v; And this one just runs recursively on both elements in the second...

How to handle initial nil value for reduce functions

swift,functional-programming,reduce

It might just be that Swift does not automatically infer the type of your initial value. Try making it clear by explicitly declaring it: var longestOfStrings = toDoItems.reduce(nil as Int?) { optionalMax($0, count($1)) } By the way notice that I do not count on $0 (your accumulator) since it is...

In underscore/lodash, how to avoid duplicate calculation in a `map` method?

javascript,functional-programming,underscore.js,lodash

transformed = _(original).map(function (c) { var coordinates = wgs2gcj(c.latitude, c.longitude); return { lat: coordinates.lat lng: coordinates.lng } }); ...

Type error calling select Standard ML

sockets,select,sml

(Thanks to bgates from #sml for pointing me in the right direction here) Two problems with the above. Firstly, I had a typo in the constructor name in the call to Socket.select. ... rds = descs [server], wrs = descs [], (* `wrs` instead of `wds` here *) exs =...

Apply a list of Functions to a Java stream's .map() method

java,lambda,functional-programming,java-8,java-stream

If lookupFunction(nvp.getName()) returns a Collection of functions, you can get a Stream of that Collection and map each function to the result of applying it to the NameValuePair : List<NameValuePair> newParamPairs = paramPairs.stream() .flatMap((NameValuePair nvp) -> lookupFunction(nvp.getName()).stream().map(func -> func.apply(nvp))) .flatMap(Collection::stream) .collect(toList()); ...

Purity, Referential Transparency and State Monad

scala,functional-programming

I guess you could say that your update itself is pure, in the sense that it only represents some mutation, but as soon as you run it all bets are off: scala> val xs = List(1.0, 2.0, 3.0).to[ArraySeq] xs: scala.collection.mutable.ArraySeq[Double] = ArraySeq(1.0, 2.0, 3.0) scala> update(0, 10).eval(xs) res0: scalaz.Id.Id[Unit] =...

functional way to accumulate pairs in java8

java,functional-programming,java-8,java-stream

You can move the map steps inside the flatMap: return Arrays.stream(names) .<Person>flatMap( name -> getTokensForPerson(name).stream() .filter(Token::isValid) .map(token -> new Person(name, token))) .collect(Collectors.toList()); This way you can access name variable as well. StreamEx-based solution is shorter, though it requires third-party library: return StreamEx.of(names) .cross(name -> getTokensForPerson(name).stream()) // Here we have the...

Functional way of doing a loop of operations on an array

java,scala,functional-programming

There are lots of useful constructor methods in the Array companion object, for example, for your situation here, you can use tabulate: val nvars: Int = 10 val vars = Array.tabulate(nvars){ someFunction } // calls someFunction on the values 0 to nvars-1, and uses this to construct the array vars...

Declaring a Ruby lambda with a yield

ruby,lambda,functional-programming

You cannot yield from a lambda directly to a nonexplicit block passed to it as you are doing now (See comments below for source provided by @cremno showing that yield may only be used in method and singleton class definitions) Source Extraction: if ((type != ISEQ_TYPE_METHOD && type != ISEQ_TYPE_CLASS)...

Java 8 Lambda expressions for solving fibonacci (non recursive way)

java,lambda,functional-programming,java-8

The simplest solution is to use a stream of Pairs: Stream.iterate(new long[]{ 1, 1 }, p->new long[]{ p[1], p[0]+p[1] }) .limit(92).forEach(p->System.out.println(p[0])); Due to the lack of a standard pair type, it uses a two-element array. Further, I use .limit(92) as we can’t evaluate more elements using long values. But it’s...

Convert loop to Maybe monad

c#,functional-programming,maybe

the answer to your comment/question is: you don't - yeah you could try it using recursive calls but this might fail horrible in C# and you are way better of with the while from x in X is just the monadic - bind (it get's translated into the SelectMany functions)...

How do you represent nested types using the Scott Encoding?

haskell,functional-programming,lambda-calculus,algebraic-data-types,scott-encoding

If the Wikipedia article is correct, then data Tree a = Node (List (Tree a)) | Leaf a has Scott encoding node = λ a . λ node leaf . node a leaf = λ a . λ node leaf . leaf a It looks like the Scott encoding is...

Scala wrong forward reference

scala,functional-programming

You have 2 problems in this code: Not explicitly specifying that the empty and cons methods are located in the companion object Stream To fix this you need to either import Stream._ into your class: sealed trait Stream[+A] { import Stream._ def take(n: Int): Stream[A] = this match { case...

Standard ML: Getting Last in List

recursion,sml

You can always raise an exception: fun last [] = raise Empty | last (x::xs) = last' x xs fun last' x [] = x | last' _ (x::xs) = last' x xs Another option (if you would pardon the pun): fun last [] = NONE | last (x::xs) =...

What is Anamorphism - example in C#

c#,functional-programming,catamorphism

LINQ's Aggregate method has the signature T Aggregate<T>(IEnumerable<T> source, Func<T, T, T> accumulator) So the corresponding unfolding would be IEnumerable<T> Unfold<T>(T seed, Func<T, Nullable<T>> accumulator) { Nullable<T> nextValue = new Nullable<T>(seed); while (nextValue.HasValue) { yield return nextValue.Value; nextValue = accumulator(nextValue); } } In functional programming, folding and unfolding must include...

Idiomatic list construction

list,haskell,functional-programming,idiomatic

The multiple call to addPoints could be replaced by a fold. As suggested in a comment, reversing your addPoint function would make things easier: addPoint' :: Point -> Polyline -> Polyline addPoint' p line = p:line So then your constructLine function could build a temporary list of the points to...

Joining a collection based on members of the type

java,functional-programming,guava,method-chaining

Solved it!! Lets say the List<A> is called Alist String join=Joiner.on("\n").skipNulls().join(Iterables.transform(Alist, new Function<A,String>(){ public String apply(A input){ return input.getb()+","+input.getc(); } })); ...

ML currying and anonymous functions

sml,currying

The function (fn x => fn y => x) is the constant function. It takes two arguments (x and y) and always returns the first argument (i.e. x). This function is applied to two arguments in all three functions a, b and c: In a the constant function is applied...

mlton gives library-related error

sml,mlton

Try executing gcc -v -x c -E - in your terminal. This will print out the header file search path that your C compiler is using. I get something like: #include "..." search starts here: #include <...> search starts here: /Users/ml9951/include . /usr/local/include /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.1.0/include /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include /usr/include /System/Library/Frameworks (framework directory)...

Hook into GHC runtime system

haskell,functional-programming,runtime,transactional-memory

(# s2#, TVar tvar# #) is an unboxed tuple. The name stg_newTVarzh is built from: The stg_ prefix, which is common to the whole GHC runtime, and stands for the spineless-tagless G-machine, an abstract machine to evaluate functional languages; newTVar which is the first part of newTVar#; the final zh,...

Questions about Vars Clojure

clojure,functional-programming

Assuming that by variable you mean a refer to a mutable storage location, I guess the main difference(depending against which language you compare) is that if you dynamically rebind the var in Clojure is on a per-thread basis. But the long answer is that you don't usually use a var...

Remove item from array using foreach - JavaScript [duplicate]

javascript,functional-programming

I would not recommend this. The forEach function iterates over the array and when you remove the current or a previous item it will skip the next item in the array. That being said if you really want to remove an item despite the problems you will run into it...

SML - Recursive function for list string

string,list,recursion,sml

Let me know if the explanations in the code make sense. fun example (xss, yss) = case (xss, yss) of (* If the 1st list is empty, then the result is an empty list. *) ([], _) => [] (* If the 2nd list is empty, then the result is...

Erlang syntax error unclear

function,variables,if-statement,functional-programming,erlang

Because expressions should be separated by ,, not ;: Val=cal(Arg1), if ... ; is the separator for if/case/receive and function clauses....

Collapse similar case statements in Scala

scala,functional-programming,pattern-matching

You can use a custom extractor to abstract the matching part away from the logic part: object Leafed { def unapply(tree: Tree) = tree match { case Node(Leaf(_, _), parent, qux) => Some((parent, qux)) case Node(parent, Leaf(_, _), qux) => Some((parent, qux)) case _ => None } } And then...

Functors with multiple inputs in Standard ML

sml,functor

Your Server functor does multiple arguments via currying. That does not work in plain SML, because it does not have higher-order functors (which SML/NJ supports as a non-standard extension). You need to use uncurried form, by introducing an auxiliary structure, like you would use a tuple or record in the...

Wildcards in Standard ML

wildcard,sml,ml

Yes, they can, but the matched list won't be empty, so the result of the null function holds, i.e., [] :: [], which is equivalent to [[]], is not an empty list. No, that's syntactically invalid. However, it can be shortened to this: fun null [] = true |...

Handling Keyboard Interrupts

sockets,exception-handling,sml,smlnj,keyboardinterrupt

You've hit a pretty big limitation with Standard ML per se, which is that the standard language does not make any provisions for concurrent programming. And you need concurrency in this particular case. Luckily, you're using SML/NJ, which has some extensions that allow concurrency support — continuations. In SML/NJ, you...

Is this definition of a tail recursive fibonacci function tail-recursive?

scala,f#,functional-programming,tail-recursion,continuation-passing

The second call to go on line 4 is not in tail position, it is wrapped inside an anonymous function. (It is in tail position for that function, but not for go itself.) For continuation passing style you need Proper Tail Calls, which Scala unfortunately doesn't have. (In order to...

How to effectively get indices of 1s for given binary string using Scala?

scala,functional-programming,higher-order-functions

You can use a filter and then map to get the index : scala> val s = "10010010" s: String = 10010010 scala> s.zipWithIndex.withFilter(_._1 == '1').map(_._2) res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 3, 6) Note: I'm using withFilter and not filter to avoid creating a temporary collection. Or you can use collect,...

Is there a lazy functional (immutable) language where functions have intermediate variables+return?

scope,functional-programming,lazy-evaluation

This is, of course, doable in a functional, declarative language like haskell. Either with let bindings or where keyword. These are just chained together in one expression. --local variables with 'where' f :: Int -> Int f x = z where z = y*2 y = x*x --local variables with...

Having trouble stepping through function that reduces an array of functions

javascript,functional-programming,reduce,higher-order-functions

It looks like you're trying to create a composition function that takes an array of functions to apply to an input, num Let's first cover a couple syntax errors. First you're missing the function keyword // your code comboFunc(num, functionsArr) { // should be function comboFunc(num, functionsArr) { Next, you've...

In simplest term, what is currying and why should this approach be favored over traditional programming paradigm?

scala,functional-programming,software-engineering,currying

Imagine a function with multiple parameters add(a,b) = a + b. This function adds two numbers. Now imagine, in some context you need a function that takes just one parameter and you'd like to have a function that adds 5. That function could look like this: adds5(x) = 5 +...

Why is `++` for Haskell List implemented recursively and costs O(n) time?

list,pointers,haskell,recursion,functional-programming

That's pretty much what the recursive solution does. It's the copying of a which takes O(n) (where n is the length of a. The length of b doesn't affect the complexity). There is really no "trick" to copy a list of n elements in O(1) time....

Is there a functional way to set a variable in javascript?

javascript,functional-programming

here I am assume the context is window which is global context function set(variablename,value){ window[variablename] = value; } hope this helps you....

Using TCP in Standard ML

sockets,tcp,sml

It turns out that an ArraySlice of Word8s is not the same thing as a Word8ArraySlice. In order to get the latter from a string, you need to call packString with an appropriate array. I decided to use Vectors instead, which meant that I could do Word8VectorSlice.full (Byte.stringToBytes res) to...

SML - Unzip tuples in one list

list,tuples,sml,unzip

I'm not entirely sure what the function you posted does, but it almost certainly won't unzip a list of 2-tuples for you. It seems to expect 3-tuples, and does some de-referencing/concatenation to boot. How did you find it? If you want a function that takes a list of 2-tuples and...

Properly implement F# Unit in C#

c#,f#,functional-programming

I'm not sure what is the best way to define Unit for usage from C#. It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way). However, you can actually find the implementation of F# unit in the core library:...

Standard ML / NJ: Loading in file of functions

functional-programming,sml

As you mentioned, the function use has type string -> unit. This means it takes a string and returns unit. When you do use test.sml, you are not giving it a string. You need to do use "test.sml" (notice the quotes)

Lazy functions evaluation in swift

ios,swift,if-statement,functional-programming,lazy-evaluation

Do not know if this is what you want,you can use function as a type func foo() { println("this is foo") } func bar() { println("this is bar") } func maybeFooOrBar(isFoo: Bool) { let myFoo = foo let myBar = bar let result = isFoo ? myFoo : myBar result()...

Accessing call stack depth in Scheme

functional-programming,scheme,tail-recursion,callstack

Racket allows you to store values in the call stack. You can use this to keep track of the depth. Here is how I would do it: #lang racket ;;; This module holds the tools for keeping track of ;;; the current depth. (module depth racket (provide (rename-out [depth-app #%app])...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java

I think, your case can be accomplished with a combination of merge, filter and take: List<Observable<HotelInfo>> hotels = new ArrayList<>(); for (URL u : urls) { Observable<HotelInfo> hotelInfo = networkAPI.askHotel(u); hotels.add(hotelInfo); } Observable.merge(hotels) .filter(h -> h.vacancy > 0) .take(1) .subscribe(h -> System.out.println("Winner: " + h), Throwable::printStackTrace); ...

Why use Object.create inside this reduce callback?

javascript,functional-programming

You kind of answered your own question: Object.create makes that prototype chain. Object.create takes as its parameter the prototype object for the object being created. var copyOfAccumulatedMap = Object.create(accumulatedMap); The old accumulatedMap is being used as the prototype for copyOfAccumulatedMap. Then copy is returned, to be the accumulatedMap the next...

First word of binary string erlang

functional-programming,erlang,pattern-matching

Although Attic's approach is correct, there is a straightforward solution (including trimming of leading spaces): first_word_bin(Bin) -> first_word_bin(ltrim(Bin), <<>>). first_word_bin(<<>>, Acc) -> Acc; first_word_bin(<<$\s, _/binary>>, Acc) -> Acc; first_word_bin(<<X, Bin/binary>>, Acc) -> first_word_bin(Bin, <<Acc/binary, X>>). ltrim(<<$\s, Bin/binary>>) -> ltrim(Bin); ltrim(Bin) -> Bin. ...

Using Diagrams library in haskell (draw binary trees)

haskell,recursion,tree,functional-programming,binary-tree

I think the problem is you're naming giving the inner nodes the same names so connectOutside connects the first names it finds (which happen to be the last nodes in your tree). You can solve this by giving each node a unique name depending on its position: diagTree :: Show...