Using a stack inside a Haskell Function - function

I want to use a stack inside a Haskell function but I don't know how to use it. My function is supposed to work like this :
Take a string
Put some elements of this input string to output string and put others to stack.
Pop elements to that output string too.
Do 2 and 3 recursively until stack is empty.
Print the output string when stack is empty.
I don't know when and where to create that stack. I couldn't figure it out myself since I'm very new at Haskell programming. Since I haven't created any code I can't show any code either. Can you tell me what the function will look like in an algorithmic way? Where should I define the stack and output string? Thanks.

One comfortable thing here is that standard Haskell list is a fine stack (natural, bearing in mind that stack is a more restricted kind of list). Your function might look something like this:
--takes one string and uses a stack to convert it to another string
doSomethingWithStack :: String -> [String] -> String
doSomethingWithStack str stack =
let str' = --here you embody your points 2 and 3
stack' = --stack top is (head stack), push is (x : stack), pop is (tail stack)
--... any change you'd want to make to any value turns into a new variable
in case stack'' of --check the final variables
[] -> str'' --if stack is empty, end
_ -> doSomethingWithStack str'' stack'' --if not, repeat
--now, to make it pretty
fancyWrapper :: String -> String
fancyWrapper str = doSomethingWithStack str [] -- empty list is an empty stack
--because you should strive to separate pure and impure functions
--, I suggest that you do the print elsewhere, say
main = do
str <- getLine
print $ fancyWrapper str
Hopefully that is neither too little nor too much. Give it a try and ask more specific questions, once you run into problems.

Related

How to partially apply a function with desired order in Elm?

Suppose I have a function that takes 3 parameters as input. How to partially apply this function in Elm so it takes first and last parameters and waits for the second parameter to return the final result?
This can be done in Ramda with R.__ which is named placeholer.
You can just wrap it in a lambda function that has the shape you want, which is what would be produced by any other means anyway:
\y -> f "x" y "z"
In a curried language I find the need to do this so rare that adding syntax sugar specifically for this use case seems unnecessary.
As glennsl says, you can wrap your function in another function with the argument order that you want. his answer assumes that you know statically what the first and third arguments are, if you don't, but just want to partially apply the first and third argument, then apply the second you can take a function like,
joinThree : String -> String -> String -> String
joinThree first second third =
first ++ second ++ third
and wrap it in a new function that calls the first function, but with a different argument order,
joinThreeWrapper : String -> String -> String -> String
joinThreeWrapper first third second =
joinThree first second third
This allows you to call this function like,
welcomeToNeverland : String -> String
welcomeToNeverland name =
let
myGreeting = joinThreeWrapper "Welcome " " to Neverland"
in
myGreeting name
Then you can use it like,
text (welcomeToNeverland "Wendy")
-- Welcome Wendy to Neverland
Writing joinThreeWrapper like this makes it a bit easier to map your function over a list like,
greetMany : List String -> List String
greetMany names =
List.map (joinThreeWrapper "Welcome " ", this is our town. ") names
so that you can do,
text (List.map (++) (greetMany ["Jesse", "Carl"]))
-- Welcome Jesse, this is our town. Welcome Carl, this is our town.
You can use flip from the core Basics module.
For instance:
> append3 x y z = x ++ y ++ z
<function> : appendable -> appendable -> appendable -> appendable
> hello = flip (append3 "Hello, ") "!"
<function> : String -> String
> hello "world"
"Hello, world!" : String

How to iterate through similar registers definition in Chisel (regmap)

I have some similar register definition, and I want to write under the regmap construct.
My code currently looks like this:
val regs = RegInit(Vec(Seq.fill(5)(0.U(32.W))))
regmap (
...
0x30 -> Seq(RegField(32,regs(0),RegFieldDesc("reg0",""),
0x34 -> Seq(RegField(32,regs(1),RegFieldDesc("reg1",""),
0x38 -> Seq(RegField(32,regs(2),RegFieldDesc("reg2",""),
0x3C -> Seq(RegField(32,regs(3),RegFieldDesc("reg3",""),
0x40 -> Seq(RegField(32,regs(4),RegFieldDesc("reg4",""),
...
)
My question, is there a way to write the above in more concise way using one of the Scala Iterators?
Another requirement I have is that I still need to be able to add register before and after this iterator (3 dots lines).
I believe ,using iterators is good against copy/paste mistakes and looks better.
Thanks in advance for any help.
I think the pattern for this would probably be something like
val regs = RegInit(Vec(Seq.fill(5)(0.U(32.W))))
val tuples = regs.zipWithIndex.map { case (reg, i) =>
(0x30 + (i * 4)) -> Seq(RegField(32,regs,RegFieldDesc(s"reg$i","")))
}
regmap(tuples :_*)
The only bit of magic there is the :_* which converts a sequence into a list of parameters.You don't need the multiple steps that I used either, I just wanted to make it easy to see what is going on.

How to debug/dump Go variable while building with cgo?

I'm trying to write a MySQL UDF in Go with cgo, in which I have a basic one functioning, but there's little bits and pieces that I can't figure out because I have no idea what some of the C variables are in terms of Go.
This is an example that I have written in C that forces the type of one of the MySQL parameters to an int
my_bool unhex_sha3_init(UDF_INIT *initid, UDF_ARGS *args, char *message) {
if (args->arg_count != 2) {
strcpy(message, "`unhex_sha3`() requires 2 parameters: the message part, and the bits");
return 1;
}
args->arg_type[1] = INT_RESULT;
initid->maybe_null = 1; //can return null
return 0;
}
And that works fine, but then I try to do the same/similar thing with this other function in Go like this
//export get_url_param_init
func get_url_param_init(initid *C.UDF_INIT, args *C.UDF_ARGS, message *C.char) C.my_bool {
if args.arg_count != 2 {
message = C.CString("`get_url_param` require 2 parameters: the URL string and the param name")
return 1
}
(*args.arg_type)[0] = C.STRING_RESULT
(*args.arg_type)[1] = C.STRING_RESULT
initid.maybe_null = 1
return 0
}
With this build error
./main.go:24: invalid operation: (*args.arg_type)[0] (type uint32 does
not support indexing)
And I'm not totally sure what that means. Shouldn't this be a slice of some sort, not a uint32?
And this is where it'd be super helpful have some way of dumping the args struct somewhere somehow (maybe even in Go syntax as a super plus) so that I can tell what I'm working with.
Well I used spew to dump the variable contents to a tmp file inside the init function (commenting out the lines that made it not compile) and I got this
(string) (len=3) "%#v"
(*main._Ctype_struct_st_udf_args)(0x7ff318006af8)({
arg_count: (main._Ctype_uint) 2,
_: ([4]uint8) (len=4 cap=4) {
00000000 00 00 00 00 |....|
},
arg_type: (*uint32)(0x7ff318006d18)(0),
args: (**main._Ctype_char)(0x7ff318006d20->0x7ff3180251b0)(0),
lengths: (*main._Ctype_ulong)(0x7ff318006d30)(0),
maybe_null: (*main._Ctype_char)(0x7ff318006d40)(0),
attributes: (**main._Ctype_char)(0x7ff318006d58->0x7ff318006b88)(39),
attribute_lengths: (*main._Ctype_ulong)(0x7ff318006d68)(2),
extension: (unsafe.Pointer) <nil>
})
Alright so huge help with #JimB who stuck with me even though I'm clearly less adept with Go (and especially CGO) but I've got a working version of my UDF, which is an easy and straight forward (and fast) function that pulls a single parameter out of a URL string and decodes it correctly and what not (e.g. %20 gets returned as a space, basically how you would expect it to work).
This seemed incredibly tricky with a pure C UDF because I don't really know C (as well as I know other languages), and there's a lot that can go wrong with URL parsing and URL parameter decoding, and native MySQL functions are slow (and there's not really a good, clean way to do the decoding either), so Go seemed like the better-than-perfect candidate for this kind of problem, for strong performance, ease of writing, and wide variety of easy to use built ins & third party libraries.
The full UDF and it's installation/usage instructions are here https://github.com/StirlingMarketingGroup/mysql-get-url-param/blob/master/main.go
First problem was debugging output. And I did that by Fprintfing to a tmp file instead of the standard output, so that I could check the file to see variable dumps.
t, err := ioutil.TempFile(os.TempDir(), "get-url-param")
fmt.Fprintf(t, "%#v\n", args.arg_type)
And then after I got my output (I was expecting args.arg_type to be an array like it is in C, but instead was a number) I needed to convert the data referenced by that number (the pointer to the start of the C array) to a Go array so I could set it's values.
argsTypes := *(*[2]uint32)(unsafe.Pointer(args.arg_type))
argsTypes[0] = C.STRING_RESULT
argsTypes[1] = C.STRING_RESULT

Haskell - have a function call a function

we are currently sitting on a task from university, which we don't fully understand (please no solution but only ideas or suggestions).
What is given is a type:
type MyType = String -> String
Now we are trying to be able to have a function, which takes 2 Strings and a function (the type) and then gives a function (type)
myCode :: String -> String -> MyType -> MyType
and we already implemented a function, which can be used as MyType one:
emptyString :: MyType
emptyString :: (\a -> "")
The task is to be able to store several 2x Strings. This is our current idea:
myCode :: String -> String -> MyType ->MyType
myCode a b c = (\x -> b)
in this case we have an input String, which is "Hello" and another one which is "World" and then as c we put in the "emptyString".
This works for one String, because when we type the following in the console:
a = (myCode "Hello" "World" emptyString) ""
we get "World" on input "a". Now the hard part: We should be able to store several of these (searching them is another task, not needed right now). We thought we might be able to use "a" now when declaring another variable:
b = (myCode "1" "2" a) "Hello" "World" emptyString "")
This would call in "b" the function saved as "a" and within this the "emptyString".
As you may have guessed - it doesn't work! And we are really at a loss on how to carry on from now.
When you reached this part, it means you took the time to understand our complicated explanation of our task - thanks a lot.
Thanks for suggestions and help in advance!
From the question linked by amalloy in the comments, it looks like you are trying to build a phonebook based on a continuation passing style like paradigm.
Basically, what is supposed to happen for your type
myCode :: String -> String -> MyType -> MyType
is that you will generate a piece of data dat = myCode a b pb, which is of type MyType. So, you can query dat with an s :: String and it will output another String. In the operation of dat s, if you expand it to the definition,
dat s = myCode a b pb s
you have access to three strings, a, b, and whatever pb s returns. You will build up functionality recursively, either by doing something with a b and s, or pushing it down the road to pb, letting the continuation handle it.
Hope this helps without giving too much away.

random line in file

This question was given to me during an interview. The interview is long over, but I'm still thinking about hte problem and its bugging me:
You have a language that contains the following tools: a rand() function, while and for loops, if statements, and a readline() method (similar to python's readline()). Given these tools, write an algorithm that returns a random line in the file. You don't know the size of the file, and you can only loop over the file's contents once.
I don't know the desired answer, but my solution would be the following:
chosen_line = ""
lines = 0
while (current_line = readline()):
if (rand(0, lines) == 0):
chosen_line = current_line
lines++
return chosen_line
Edit: A good explanation why this works was posted in this comment.
One method, guaranteeing a uniform distribution:
(1) Read the file line-by-line into an array (or similar, e.g. python list)
(2) Use rand() to select a number between 0 and largest index in the array.
Another, not guaranteeing a uniform distribution:
Read each line. On each read, also call rand(). If over a threshold, return the line.
Although similar to Marcin's third option, Luc's implementation always returns the first line, while parsing the whole file.
It should be something like:
chosen_line = ""
treshold = 90
max = 100
while chosen_line == "":
current_line = readline()
if (rand(0, max) > treshold):
chosen_line = current_line
print chosen_line
You could also return current_line in the case no line was chosen and you read the whole file.